1

我试图将带有过滤器的ng-repeat的结果传递给子指令,但我得到了无限的摘要循环错误。如何将ng-repeat过滤列表传递给自定义指令

Plnkr

HTML

<!DOCTYPE html> 
<html> 

<head> 
    <script data-require="[email protected]*" 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); 
     }); 
    } 
    } 
}); 

你可以看到,填充正确的过滤列表中,但有一个无限消化循环

回答

0

我发现问题了

我肩膀d一直在使用$ watchCollection而不是$ watch在filteredItems

1

尝试取出require:和一切在scope: - 了解更多关于隔离作用域这里https://docs.angularjs.org/guide/directive &这里https://github.com/angular/angular.js/issues/9554

而且,你不需要controller:function(),如果你有link:function()

你的指令应该看起来更像是这样的:

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

好运

+0

谢谢,我已经对代码进行了编辑。我仍然不确定如何在列表过滤时触发一个函数。我在scope.filteredItems上放置了一个$ watch,但它仍然导致无限的摘要循环 – Aeisys

相关问题