43

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];      
   }
});
Jakub Kukul
  • 12,032
  • 3
  • 54
  • 53
user1477955
  • 1,652
  • 8
  • 23
  • 35

5 Answers5

47

You need to tell angular that the values have changes:

$scope.loadNewFilter = function (){
    $scope.filter = [1,2,3];      
    $scope.$apply();
}
Chris Charles
  • 4,406
  • 17
  • 31
  • 3
    @user1477955 :http://jsfiddle.net/6nssg30q/6/ button is out of scope of controller. It works now – RahulB Sep 15 '14 at 08:27
  • This solved an issue I was having wherein adding items to an array via a callback did not update the ng-repeat automatically. Calling $source.$apply(); right after adding a new item caused it to show up just fine. – Magic Marbles Oct 24 '16 at 22:43
9

You have placed <button ng-click="loadNewFilter()"> filter now</button> out of controller scope.

Gaurav
  • 28,447
  • 8
  • 50
  • 80
8

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

aoakeson
  • 602
  • 1
  • 8
  • 20
2

After receiving your filter called $scope.$apply() as following: It is refresh your scope.

$scope.$apply(function() {
     // your code
});
Mahesh
  • 1,063
  • 1
  • 12
  • 29
0

I didnt need to use $scope.apply() to see the update. 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.
Duilio
  • 876
  • 1
  • 10
  • 15