2013-03-11 64 views
12

我在這裏丟失了一些明顯的東西。在我的指令中,我有一個可用的雙向數據綁定,但是我似乎無法使用$ scope。$ watch()來監視指令的父範圍js對象上可能發生的更改。

http://jsfiddle.net/Kzwu7/6/

正如你所看到的,當我嘗試使用$上attrs.dirModel觀看所產生的價值是不確定的,並沒有進一步看,即使我修改短暫延遲後的對象。我也試過在$ watch語句中使用(而不是使用)true標誌。

HTML:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> 
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script> 

<div ng-app="test" ng-controller="MainCtrl"> 
    <dir dir-model="model"></dir> 
    <p>{{model.tbdTwoWayPropA}}</p> 
</div> 

<script type="text/ng-template" id="template"> 
    <div class="test-el">{{dirModel.tbdTwoWayPropB}}</div> 
</script> 

JS:

var app = angular.module('test', []); 

app.controller("MainCtrl", [ 
    "$scope", "$timeout", 
    function($scope, $timeout){ 
     $scope.model = { 
      tbdTwoWayPropA: undefined, 
      tbdTwoWayPropB: undefined, 
      tbdTwoWayPropC: undefined 
     } 

     // TBD Ajax call 
     $timeout(function(){ 

      // alert("Model updated, but $scope.$watch isn't seeing it."); 

      $scope.model.tbdTwoWayPropA = 1; 
      $scope.model.tbdTwoWayPropB = 30; 
      $scope.model.tbdTwoWayPropC = [{ a: 1 },{ a: 2 },{ a: 3 }]; 

     }, 2000) 
    } 
]); 

app.directive('dir', [ 
    "$timeout", 
    function($timeout) { 
     return { 
      restrict: "E", 
      controller: function($scope){ 
       $scope.modifyTwoWayBindings = function(){ 

        // Two-way bind works 
        $scope.dirModel.tbdTwoWayPropA = 2; 
       } 

       $timeout(function(){ 
        $scope.modifyTwoWayBindings(); 
       }, 4000); 
      }, 
      scope: { 
       dirModel: '=' 
      }, 
      template: $("#template").html(), 
      replace: true, 
      link: function($scope, element, attrs) { 

      $scope.$watch(attrs.dirModel, handleModelUpdate, true); 

       // alert(attrs.dirModel); 

       function handleModelUpdate(newModel, oldModel, $scope) { 
        alert('Trying to watch mutations on the parent js object: ' + newModel); 
       } 
      } 
     } 
}]); 

回答

19

由於您使用 '=',你有一個本地指令scope屬性dirModel。只要$注意:

$scope.$watch('dirModel', handleModelUpdate, true); 
+0

謝謝。你碰巧知道了解更多關於「本地指令範圍屬性」的好資源。以前我只能看到訪問attributes參數的例子。 最終的JS小提琴供用戶參考。 http://jsfiddle.net/Kzwu7/8/ – BradGreens 2013-03-11 18:15:43

+0

@BradGreens,好吧,它在不太容易理解的[指令頁面](http://docs.angularjs.org/guide/directive )在「指令定義對象」部分下。另請參閱http://stackoverflow.com/questions/14050195/what-is-the-difference-between-and-in-directive-scope/14063373#14063373,http://stackoverflow.com/questions/14908133/what- is-the-difference-between-vs-in-in-angularjs,和http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs/14049482#14049482(請參閱底部附近的「指令」部分)。 – 2013-03-11 18:29:11

+0

我讀過很多遍了;)。我想現在我特別想知道哪些角度方法會接受該屬性的字符串表示作爲參數。即$ observe('attr',fct),$ set('attr','val'),$ watch('attr',fct)等等......字符串表示有點神奇。 – BradGreens 2013-03-11 18:58:46