44

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

5 Answers 5

48

You need to tell angular that the values have changes:

$scope.loadNewFilter = function (){
    $scope.filter = [1,2,3];      
    $scope.$apply();
}
Sign up to request clarification or add additional context in comments.

2 Comments

@user1477955 :jsfiddle.net/6nssg30q/6 button is out of scope of controller. It works now
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.
9

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

1 Comment

Funny, my next issue was how to call a click event in angularJS. Thank you :) +1
8

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

2 Comments

Precisely the same issue for me! Thank you - I'd not ever have expected tracyBy to cause a problem - I've only known it solves issues before!
@Meliodas you can use $index without trackBy
2

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

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.