AngularJS filter triggers infinite $digest loop

前端 未结 2 1342
星月不相逢
星月不相逢 2021-01-19 01:05

I want to use a filter expression like values | filter:value1 to hide or show a div, where values and value are both declared on the s

2条回答
  •  不思量自难忘°
    2021-01-19 01:47

    The answer to the problem is in the error description that Angular provides.

    One common mistake is binding to a function which generates a new array every time it is called

    This is basically what filter does, each time it returns new array:

    // some more code
    var filtered = [];
    for ( var j = 0; j < array.length; j++) {
      var value = array[j];
      if (predicates.check(value)) {
        filtered.push(value);
      }
    }
    return filtered;
    

    When Angular's digest loop runs for the first time it gets an array containing 'bar' and an empty array. Then Angular will run digest loop again to check if the model is stable. It will get new arrays (instances) and it will think that the model has changed. This will cause another digest loop, and so on.

    You should check if your array contains values and ng-show on that. E.g. Determine whether an array contains a value

    Check out this modified jsbin: http://jsbin.com/nujineci/5/edit

提交回复
热议问题