AngularJS $ scope。$ watch on json对象无法在指令内工作

时间:2013-03-11 17:18:07

标签: angularjs

我在这里遗漏了一些明显的东西。在我的指令中,我有一个工作的双向数据绑定,但我似乎无法使用$ scope。$ watch()来监视指令的父作用域js对象上可能发生的更改。

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

正如你所看到的,当我尝试在attrs.dirModel上使用$ watch时,结果值是未定义的,没有进一步观察,即使我在短暂的延迟后修改了对象。我也尝试在$ 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);
              }
          }
      }
}]);

1 个答案:

答案 0 :(得分:19)

由于您使用的是'=',因此您有一个本地指令范围属性dirModel。只需观看:

$scope.$watch('dirModel', handleModelUpdate, true);
相关问题