简体   繁体   English

AngularJS - 刷新ng-repeat

[英]AngularJS - refresh ng-repeat

I'm using ng-repeat to display a collection of values. 我正在使用ng-repeat来显示一组值。 My filter options changes according to an ajax call to server. 我的过滤器选项根据对服务器的ajax调用而更改。 How can I refresh the ng-repeat after the filter parameters have been received? 如何在收到过滤器参数后刷新ng-repeat?

js fiddle 小提琴

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];      
   }
});

You need to tell angular that the values have changes: 你需要告诉angular值值有变化:

$scope.loadNewFilter = function (){
    $scope.filter = [1,2,3];      
    $scope.$apply();
}

您已将<button ng-click="loadNewFilter()"> filter now</button>放置在控制器范围之外。

在我的情况下,我在我的ng-repeat中有一个trackBy,不得不将其删除以使其更新。

After receiving your filter called $scope.$apply() as following: It is refresh your scope. 收到名为$ scope。$ apply()的过滤器后,如下所示:刷新范围。

$scope.$apply(function() {
     // your code
});

I didnt need to use $scope.apply() to see the update. 我不需要使用$ scope.apply()来查看更新。 What solved this error for me was to make sure: 为我解决这个错误的原因是确保:

  1. The update was being called from inside the controller. 正在从控制器内部调用更新。
  2. The controller that called the update was the same that contained the ng-repeat. 调用更新的控制器与包含ng-repeat的控制器相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM