Search code examples
javascriptangularjsangularjs-directiveangularjs-ng-repeatangularjs-filter

How to pass ng-repeat filtered list to custom directive


I'm trying to pass the result of an ng-repeat with a filter into a child directive, but I am getting an infinite digest cycle error.

Plnkr

HTML

<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@*" data-semver="4.0.0" src="https://code.angularjs.org/latest/angular.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-app="myApp">
  <table ng-controller="repeatCtrl">
    <thead></thead>
    <tr ng-repeat="x in (filteredItems = (list | filter: evens))">
      <td>{{x}}</td>
    </tr>
    <tfoot>
      <tr>
        <td footer-directive="" repeat-ctrl="repeatCtrl" list='filteredItems'></td>
      </tr>
    </tfoot>
  </table>
</body>

</html>

JS

var app = angular.module("myApp", []);

app.controller("repeatCtrl", function($scope) {
  var foo = [];
  for (i = 0; i < 100; i++) {
    foo.push(i);
  }
  $scope.list = foo;
  $scope.evens = function(val) {
    return (val % 2 === 0);
  };

});

app.directive('footerDirective', function() {
  return {
    restrict: 'EA',
    template: 'List: {{filteredItems}}',
    link: function(scope, element, attrs) { //Infinite digest loop
      scope.$watch('filteredItems', function(newValue, oldValue) {
        console.log(newValue);
      });
    }
  }
});

You can see that the filtered list is properly populated, but there's an infinite digest loop


Solution

  • I found the problem

    I should have been using $watchCollection instead of $watch on the filteredItems