NG-Repeat 更新范围时更新不干净

NG-Repeat doesn't update cleanly when scope is updated

所以我有一个工作区列表:

<li class="workspace-object" ng-repeat="w in workspaces | filter:searchQuery" ng-click="selectWorkspace(w)">
    <a href="" class="workspace-link">{{w.name | titleCase }}</a>
</li>

那个列表通过一些函数在数据库中更新,然后我调用下面的 loadWorkspaces 函数,re-populate $scope.workspaces object

$scope.loadWorkspaces = function() {
  APIService.getWorkspaces().then(function(data){
    $scope.workspaces = data;
  });
}

发生这种情况时,$scope.workspaces 在注销后会立即读取正确的更新信息,但是 ng-repeat 在更新到正确的列表之前会重复。我不知道为什么会这样。有任何想法吗? 在此示例中,我正在更新工作区标题,并且该更新运行 loadworkspaces 函数。

试试这个...

w in workspaces track by $index

When the contents of the collection change, ngRepeat makes the corresponding > changes to the DOM:

  • When an item is added, a new instance of the template is added to the DOM.
  • When an item is removed, its template instance is removed from the DOM.
  • When items are reordered, their respective templates are reordered in the DOM.

By default, ngRepeat does not allow duplicate items in arrays. This is because when there are duplicates, it is not possible to maintain a one-to-one mapping between collection items and DOM elements.

If you do need to repeat duplicate items, you can substitute the default tracking behavior with your own using the track by expression.

For example, you may track items by the index of each item in the collection, using the special scope property $index

接受的答案对我没有帮助(使用Angular 1.1.10),我的重复仍然更新延迟。在我开始工作之前,我挣扎了很长时间。

而不是像这样重复我的自定义指令;

<my-directive ng-repeat="item in myarray track by item.id" some-binding="item"></my-directive>

我(神奇地)在将 ng-repeat 移动到(非指令)父元素后让它工作,如下所示:

<div ng-repeat="item in myarray track by item.id">
    <my-directive some-binding="item"></my-directive>
</div>