1
我有一個ng-repeat
,通過一個過濾器循環一個資源對象的數組,像這樣。
<div ng-repeat='item in items | filter: { hidden: false}'>
<div my-custom-directive ng-model='item'></div>
</div>
然後,在指令中,我想監視每個資源對象的變化。
myApp.directive('myCustomDirective', function(){
return {
restrict: 'A',
replace: true,
scope: {
myDirectiveItem: '=ngModel'
},
template: '<button ng-click="myCustomDirective.hidden = true">Hide</button>',
link: function(scope) {
scope.$watch('myDirectiveItem', function(oldValue, newValue){
console.log('I have changed'); // Never called
}, true);
}
};
});
但是,$ watch回調從來沒有被要求改變對象。我認爲這是因爲在循環中,過濾器優先,所以監視的資源對象不再在該範圍內可用。
如何強制$ watch回調在對象從集合中移除之前執行?
//編輯
我想指出的是,如果我在我的代碼一切刪除| filter: { hidden: false }
按預期工作,並顯示I have changed
。它只是不適用於過濾器。
你應該看myDirectiveItem沒有項目。 –
由於Gruff Bunny說你應該關注myDirectiveItem,因爲你的指令中的範圍對於父範圍中的'item'沒有任何想法 – maurycy
感謝您指出這一點,我在示例代碼中糾正了這一點。但這不是實際的問題。 –