【问题标题】:AngularJS : what's the difference between these two lines?AngularJS:这两行有什么区别?
【发布时间】:2013-07-07 18:07:44
【问题描述】:
$scope.init = function() {
  return $scope.items = basketService.items;
};

ng-repeat = "item in items"

使用 $scope.items + 刷新 $scope.items 并进行广播。

$scope.getItems = function() {
  return basketService.items;
};

ng-repeat = "item in getItems()"

将 basketService.items 复制到 $scope.items 是必须完成的,还是与 getItems()(速度、内存...)相同?

【问题讨论】:

  • 如果你把 CoffeeScript 转换成 JavaScript,你会得到更多的答案。
  • 在第一个示例中,$scope.items = basketService.items,您不是在复制,而只是在设置参考。只要对 basketService.items 进行操作(例如,使用 angular.copy() 或 splice() 来更改服务中的 items)并且不重置(即,未完成类似的操作:items = newItemsArrayFromServer),就会有无需刷新 $scope.items ——它将始终引用服务的数组,并且 ng-repeat 会注意到任何更改。

标签: javascript jquery angularjs binding


【解决方案1】:

我不相信它们之间有区别,这实际上只是风格问题。看看我创建的这个(非常粗糙和做作的)小提琴:http://jsfiddle.net/digitalzebra/92gA6/

这是一个非常混乱的控制器:

angular.module("foobar", []).controller("lol", function($scope) {
   $scope.items = ["loe", "le", "effe"];
    var blah = ["leoele", "elelkej", "elfkjflkje"];

    $scope.doStuff = function() {
      $scope.items.push("eee", "eeelkjf");  
    };

    $scope.getItems = function() {
        return blah;
    }

    $scope.doOtherStuff = function() {
      blah.push("elejlee'e");  
    };
});

这是我的 HTML:

<div ng-app="foobar">
    <div ng-controller="lol">

       <b>First list:</b>
       <div ng-repeat="item in items">
           {{item}}
       </div>

       <b>Second list:</b>
       <div ng-repeat="item in getItems()">
           {{item}}
       </div>
        <button ng-click="doStuff()">Click me</button>
        <button ng-click="doOtherStuff()">Do Other stuff</button>
    </div>
</div>

请注意,这两种变体都可以工作,并且都会为您提供两种方式绑定等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-06
    • 2012-06-12
    • 2017-04-06
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多