我有兩個指令:
directives.parentDirective = function(){
return{
restrict: 'A',
scope: true,
controller : function($scope){
$scope.childs = {};
this.registerChild = function(ctrl, type){
$scope.childs[type] = ctrl;
};
this.triggerChange = function(ctrl, type){
$scope.childs[type] = ctrl;
};
},
link: function(scope, element, attrs) {
scope.$watchCollection('childs', function(value){
console.debug("WATCH triggered for ");
console.debug(value);
});
}
};
和
directives.childDirective = function(){
return{
restrict: 'A',
require : ['ngModel', '^parentDirective'],
scope: {
'model' : '=ngModel'
},
link: function(scope, element, attrs, ctrl) {
ctrl[1].registerChild(ctrl[0],ctrl[0].$name); //Works nice
scope.$watch('model', function(value){
ctrl[1].triggerChange(ctrl[0], ctrl[0].$name);
//the call to triggerChange works ok.
});
}
};
的HTML看起來像這樣:
<div parentDirective="so rocks">
<input type="text" ng-model="user.name" childDirective="whatever"/>
</div>
而控制器非常基本:只需要
$scope.user={name:"batman";}
會發生什麼情況是parentDirective $ watchCollection不會收到任何更改。
它確實捕獲了最初的registerChild函數。
我試圖把一個範圍。$ apply();但沒有運氣。
我真的不明白你在做什麼,但如果你發佈了一個工作小提琴,它會有所幫助。 – Mosho
'$ watchCollection'調用應該可以工作。作爲完整性檢查,嘗試使用一些不同的輸入參數調用triggerChange函數來查看監視觸發器。它看起來不像'ctrl [0]'和'ctrl [0]。$ name'將會改變你在這裏包含的代碼。 – miqid
@miqid ctrl [0]。$ viewValue會改變。我不確定$ watchCollection是遞歸地工作。我調整了一些代碼,並意識到在沒有使用對象集合的情況下,它是真正的工作。 – Ant