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

相關問題