JayPrime2012
JayPrime2012

Reputation: 2692

Why is my $watch not getting called?

I just don't understand why my $watch is NOT called a second time with the updated value of "entity".

  .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

Upvotes: 0

Views: 236

Answers (1)

Jason
Jason

Reputation: 15931

Watch should be the name of the property to be watched, try scope.$watch("entity", ..., if you want to deep watch (that is object properties) call it with true as the last parameter.

scope.$watch("entity", function() { ... }, true);

Upvotes: 2

Related Questions