Angular.js $watch on object..并不认为添加属性是一个变化



在Angular.js中,我有这个指令:

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

在我的服务中,我为它提供StatusTrackerService.eventCollection并为eventCollection添加属性:

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

当我添加一个属性到eventCollection时,$watch没有检测到变化。在我看来,向对象eventCollection添加属性会改变对象。为什么$watch没有检测到这个变化?我真的不想使用$watchCollection,因为它会检测到StatusTrackerService的任何更改

您需要对该属性进行深度监视。您可以通过在手表上设置object equality的第三个参数来实现。

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

Plnkr

相关内容

最新更新