0

我只是不明白为什么我的 $watch没有第二次调用“实体”的更新值。

  .directive('myParent', function() {
  return {
    controller: function($scope, $log) {
      $scope.$on('thingChanged', function(e, newVal) {
        $log.log('thingChanged event hit...');
        $scope.$apply(function() {
           $scope.thing = newVal;
        });
      });
    },
    template: '<div><div my-child entity="thing" v="{{thing.awesome}}"></div><div my-child2></div></div>'
  };
})
.directive('myChild', function($parse, $log) {
  return {
    controller: function($scope) {
    },
    scope: {
      entity: '=',
      v: '@'
    },
    link: function(scope, element, attrs) {
      $log.log('v in link:');
      $log.log(scope.v);
      attrs.$observe('v', function(v) {
        $log.log('v in observe in link:');
        $log.log(v);
      })
      $log.log('entity in link:');
      $log.log(scope.entity);
      scope.$watch(scope.entity, function(nv, ov) {
        $log.log('$watch detected change: ');
        $log.log(scope.entity);
      });
    }, 
    template: '<span>{{v}}</span>-<span>{{entity}}</span>'
  };
})
.directive('myChild2', function($parse, $log, $timeout) {
  return {
    controller: function($scope) {
      var count = 0;

      $timeout(function() {
        $scope.$emit('thingChanged', { awesome: 'cool'+count++ });
      }, 2000);
    },
    scope: true,
    link: function(scope, element, attrs) {
    }, 
    template: '<span><button ng-click="change()"</span>'
  };
})

Plunker:http ://plnkr.co/edit/2jfa1dcwguO400zRjJxU?p=preview

4

1 回答 1

2

watch 应该是要监视的属性的名称,try scope.$watch("entity", ...,如果要深度监视(即对象属性)将其true作为最后一个参数调用。

scope.$watch("entity", function() { ... }, true);
于 2013-10-28T15:19:25.490 回答