1

我想在後鏈接函數的屬性上應用$watch

我的代碼是這樣的:

compile: function(){ 
    return { 
     post:function(scope,element){ 
      scope.$watch('scope.x', function(){ 
       console.log(scope.x); 
      }) 
     } 
    } 
} 

加載頁面時,它會執行一次。我無法弄清楚有什麼不對嗎?

編輯:

我正在使用角柵格來顯示網格中的各種圖表。我的index.html的樣子:

<div gridster> 
    <ul> 
     <chart ng-repeat="chart in charts"> 
     </chart> 
    </ul> 
</div> 

圖是另一指令,以期:

<li gridster-item row="grid_row" col="grid_col"> 

腳本文件包含:

module.directive('chart', ['', 
    function() { 
     return { 
      restrict: 'E', 
      scope: { 
        grid_col: '=col', 
        grid_row: '=row', 
      }, 
      compile: function(element, attrs) { 
       return { 
        post: function(scope, element, timeout) { 
         scope.$watch('grid_col', function() { 
         console.log(scope.grid_col); 
         }) 
        } 
       } 
      } 
     }; 
    } 
]); 

回答

0

提供scopestring你不應該提到$watch

scope.$watch('x', function(){ 
    console.log(scope.x); 
}) 

$watch超過範圍將放置內部$$觀察者內$scope & evaluats對象上的每個消化循環對範圍內的每個字符串值。

+0

我試過了,但無濟於事,它第一次工作,但沒有打印後在控制檯中。 – user3035998

+0

@ user3035998你能爲我提供一個plunkr嗎? –