dman
dman

Reputation: 11064

Angular.js $watch on object....does not consider adding property a change

In Angular.js, I have this in my directive:

    scope.$watchCollection(function(){
          return StatusTrackerService.eventCollection
      }, function(){
          console.log("ssssssssssss");
          console.log(StatusTrackerService);
          console.log("ssssssssssss");
      });

In my service, I am feeding it StatusTrackerService.eventCollection and add a property to eventCollection:

    function runEventCheck(account, eventId) {
        url = urlBuilder(account, eventId);

        eventCollection[referenceVipLabel.vipLabel] = new NewStatusEvent(account, eventId, url);
    }
    return { runEventCheck: runEventCheck,
             eventCollection: eventCollection,
             referenceVipLabel: referenceVipLabel
    };
});

When I add a property to eventCollection, $watch does not detect a change. It seems to me adding a property to object eventCollection would change the object. Why isn't $watch detecting this change? I don't really want to use $watchCollection because then it detects any changes to StatusTrackerService.

Upvotes: 2

Views: 96

Answers (1)

PSL
PSL

Reputation: 123739

You need to do a deepwatch on the property. You can do it by setting the third argument for object equality on the watch.

 scope.$watch(function(){
      return StatusTrackerService.eventCollection; 
  }, function(v){
       console.log(v);
   }, true); //<-- Here

Plnkr

Upvotes: 3

Related Questions