11

在我看来,我有以下代码:

<li ng-repeat="i in items">{{i.id}}</li>

我希望在ng-repeat添加/删除新值时动态触发items. 例如,如果一个新元素被添加到开头,items那么它应该在开始时动态呈现到 DOM 中,类似地,如果一个元素被添加到该items项目的末尾,则应该作为最后一个列表项呈现。DOM 的这种动态变化是否可能在角度上进行?

4

2 回答 2

10

ng-repeat应该以这种方式开箱即用。但是,您需要pushunshift进入阵列,以便正确的手表会触发。Angular 将通过引用跟踪数组。

这是一个工作的plunker

HTML:

<html ng-app="myApp">

  <head>
    <script data-require="angular.js@*" data-semver="1.2.0" src="http://code.angularjs.org/1.2.0/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="Ctrl">
    <h1>Hello Plunker!</h1>
    <div ng-repeat="item in items">
      {{ item }}
    </div>
    <button ng-click="add()">Add</button>
  </body>

</html>

JS:

var myApp = angular.module('myApp', []);

myApp.controller('Ctrl', function($scope) {

    $scope.items = ['hi', 'hey', 'hello'];

    $scope.add = function() {

      $scope.items.push('wazzzup');
    }
  });
于 2013-11-13T11:52:00.547 回答
1

您可以使用 $rootScope 而不是 $scope 来设置属性项。

这样该属性是全局的并且将被更新。

myApp.controller('Ctrl', function($scope, $rootScope) {

    $rootScope.items = ['hi', 'hey', 'hello'];

    $scope.add = function() {
        $rootScope.items.push('wazzzup');
    }
});
于 2015-10-02T13:55:23.627 回答