Javascript AngularJS - 刷新 ng-repeat
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25843515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS - refresh ng-repeat
提问by user1477955
I'm using ng-repeat to display a collection of values. My filter options changes according to an ajax call to server. How can I refresh the ng-repeat after the filter parameters have been received?
我正在使用 ng-repeat 来显示一组值。我的过滤器选项根据对服务器的 ajax 调用而改变。收到过滤器参数后,如何刷新 ng-repeat?
Template
模板
<div>
<div data-ng-controller="myCtrl">
<ul>
<li data-ng-repeat="item in values | filter:filterIds()">
<code>#{{item.id}}</code> Item
</li>
</ul>
</div>
</div>
<button ng-click="loadNewFilter()"> filter now</button>
Angular
角
var app = angular.module('m', []);
app.controller('myCtrl', function ($scope) {
$scope.values = [
{id: 1},
{id: 2},
{id: 3},
{id: 4},
{id: 5},
{id: 6}
];
$scope.filter = [1,2,3,4,5,6];
$scope.filterIds = function (ids) {
return function (item) {
var filter = $scope.filter;
return filter.indexOf(item.id) !== -1;
}
}
$scope.loadNewFilter = function (){
$scope.filter = [1,2,3];
}
});
回答by Chris Charles
You need to tell angular that the values have changes:
您需要告诉 angular 值发生了变化:
$scope.loadNewFilter = function (){
$scope.filter = [1,2,3];
$scope.$apply();
}
回答by aoakeson
In my case I had a trackBy in my ng-repeat and had to remove it to get it to update.
就我而言,我的 ng-repeat 中有一个 trackBy,必须将其删除才能更新。
回答by Gaurav
You have placed
<button ng-click="loadNewFilter()"> filter now</button>out of controller scope.
您已
<button ng-click="loadNewFilter()"> filter now</button>超出控制器范围。
回答by Mahesh
After receiving your filter called $scope.$apply() as following: It is refresh your scope.
收到名为 $scope.$apply() 的过滤器后,如下所示:刷新您的范围。
$scope.$apply(function() {
// your code
});
回答by Duilio
I didnt need to use $scope.apply() to see the update. What solved this error for me was to make sure:
我不需要使用 $scope.apply() 来查看更新。为我解决这个错误的是确保:
- The update was being called from inside the controller.
- The controller that called the update was the same that contained the ng-repeat.
- 正在从控制器内部调用更新。
- 调用更新的控制器与包含 ng-repeat 的控制器相同。

