2014-07-02 43 views
0

我有一個編碼像這樣的自定義指令:如何從指令內部觀察變量的變化?

angular.module('client.core.directives') 
    .directive('containerlayout', function() { 

     function link(scope, el, attr) { 
      scope.$watch(['xdim', 'ydim', 'numOrder'], function() { 
        console.log("Watch Xdim/Ydim/numOrd change"); 
        // do something when these changesd 
       }, true); 
      scope.$watch('labels', function (labels) { 
        // do something when labels array changes 
       }, true); 

      } 

     return { 
      link: link, 
      restrict: 'E', 
      scope: { geometry: '=geometry', xdim: '=xdim', 
       ydim: '=ydim', numOrder: '=numorder', labels: '=labels', 
       states: '=states', emptyToSkipped: '=emptytoskipped' } 
    }; 

,我有以下聲明:

<containerlayout geometry="rect" xdim="cont.xdim" 
    ydim="cont.ydim" numorder="1" labels="cont.labels" 
    states="cont.states" emptytoskipped="emptytoskipped" 
    class="ng-isolate-scope"></containerlayout> 

,但是當我改變,說$ scope.cont.xdim或其他一些變量,沒有任何反應,手錶也沒有發射。

請注意,xdim和ydim是整數,標籤是數組。

我該如何在指令中聲明事物,以便它能夠觀察變量?他們是否需要首先在控制器中初始化成功的工作?如果可能的話,我需要留在孤立的範圍內。

回答

1

$watch('propertyName', func)手錶只有一個$scope.propertyName

如果你想觀看幾個屬性,你需要$watchCollection('[propertyName, anotherPropertyName]', func)

scope.$watchCollection('[xdim, ydim, numOrder]', function (valuesArray) { 
    console.log("Watch Xdim/Ydim/numOrd change", valuesArray); 
}, true); 

請問您的例子中的觀察者觸發器是否爲labels?它應該,因爲它只是一個包含數組的屬性。

+0

另一個問題是隔離範圍,這意味着你沒有與控制器通信... – BorisD

+1

那麼,Askar已通過'='將所有這些變量傳遞到指令。所以他們可以訪問。 – gorpacrate