如何将 ng-repeat 过滤列表传递给自定义指令

How to pass ng-repeat filtered list to custom directive

我试图将带有过滤器的 ng-repeat 的结果传递到子指令中,但我遇到了无限摘要循环错误。

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

您可以看到过滤列表已正确填充,但存在无限摘要循环

尝试删除 require:scope: 下的所有内容 -- 在此处阅读有关独立作用域的更多信息 https://docs.angularjs.org/guide/directive & here https://github.com/angular/angular.js/issues/9554

此外,如果您有 link:function()

,则不需要 controller:function()

您的指令应该更像这样:

app.directive('footerDirective', function() {
return {
    template: 'List: {{list}}',
    link: function(scope, element, attrs) {
        console.log(scope.list)
    }
}});

祝你好运

我找到问题了

我应该在 filteredItems 上使用 $watchCollection 而不是 $watch