2013-06-18 34 views
0

爲什麼$ scope.watch不能與'model'配合使用? http://jsfiddle.net/lesouthern/8PUtP/5/雙向數據綁定手錶

.directive('testDirective',function() { 
    return { 
     restrict : 'A', 
     scope : { 
      model : '=ngModel' 
     }, 
     link : function($scope,$element,$attrs) { 
      $scope.$watch('model',function(x) { 
       console.log('this is model: ' + x); 
      }); 
     } 
    } 
}); 
+1

在這種情況下 「=」 應爲 「@」[小提琴](http://jsfiddle.net/jcsYE/) – rGil

+1

[這個答案](HTTP:/ /stackoverflow.com/a/14063373/2013981)總結。 – rGil

回答

1

請參閱this question。這是您的更正代碼:

return { 
    restrict : 'A', 
    link : function($scope, $element, $attrs) { 
     $scope.$watch($attrs.ngModel, function(x) { 
      console.log('this is model: ' + x); 
     }); 
    } 
} 
+0

謝謝您的幫助。這個解決方案的問題是我需要限制這個指令的範圍。我如何看這個輸入的值,並用這個範圍變量綁定兩種數據? – koolunix

+0

@ koolunix恕我直言,你應該接受這個答案,因爲你在答案中使用完全相同的解決方案。 – Stewie

+0

完整的問題需要限制指令的範圍。上面顯示的內容不回答此問題 – koolunix