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?
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]; } });
AngularJS ng-repeat Directive The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.
Each ng-repeat creates a child scope with the passed data, and also adds an additional $index variable in that scope. So what you need to do is reach up to the parent scope, and use that $index .
Stay on the bleeding edge of your favorite technologies. $index is a way to show which iteration of a loop you're in. If we set up an ng-repeat to repeat over the letters in 'somewords', like so: <div ng-app="app"> <div ng-repeat="item in 'somewords'.split('')"> {{$index + 1}}.
An AngularJS module that allows you to control when you release new features in your app by putting them behind feature flags/switches.
You need to tell angular that the values have changes:
$scope.loadNewFilter = function (){ $scope.filter = [1,2,3]; $scope.$apply(); }
In my case I had a trackBy in my ng-repeat and had to remove it to get it to update.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With