2014-03-31 38 views
0

我有兩個指令:

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();但沒有運氣。

+1

我真的不明白你在做什麼,但如果你發佈了一個工作小提琴,它會有所幫助。 – Mosho

+1

'$ watchCollection'調用應該可以工作。作爲完整性檢查,嘗試使用一些不同的輸入參數調用triggerChange函數來查看監視觸發器。它看起來不像'ctrl [0]'和'ctrl [0]。$ name'將會改變你在這裏包含的代碼。 – miqid

+0

@miqid ctrl [0]。$ viewValue會改變。我不確定$ watchCollection是遞歸地工作。我調整了一些代碼,並意識到在沒有使用對象集合的情況下,它是真正的工作。 – Ant

回答

1

在您必須參考使用dash-delimited形式指令的DOM,沒有駝峯規範化的形式:

<div parent-directive="so rocks"> 
    <input type="text" ng-model="user.name" child-directive="whatever"/> 
</div> 

這裏是一個plunker,顯示出父表工作: http://plnkr.co/wNUcsWuGQvCt779kB6ij

由於miqid在評論中指出,兒童手錶沒有改變類型。我將類型更改爲數字,並在每個表中增加數字,以強制更改以供父級查看。

+0

' - '是一個錯字。我的代碼不工作,因爲我懷疑$ watchCollection不能遞歸觀察。 – Ant

相關問題