Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - refresh ng-repeat

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];          } }); 
like image 586
user1477955 Avatar asked Sep 15 '14 08:09

user1477955


People also ask

What is Ng-repeat in AngularJS?

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.

How do you pass an index in NG-repeat?

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 .

What is $Index in AngularJS?

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}}.

What is Flag in AngularJS?

An AngularJS module that allows you to control when you release new features in your app by putting them behind feature flags/switches.


2 Answers

You need to tell angular that the values have changes:

$scope.loadNewFilter = function (){     $scope.filter = [1,2,3];           $scope.$apply(); } 
like image 106
Chris Charles Avatar answered Sep 24 '22 10:09

Chris Charles


In my case I had a trackBy in my ng-repeat and had to remove it to get it to update.

like image 29
aoakeson Avatar answered Sep 22 '22 10:09

aoakeson