2014-07-01 29 views
0

如果对象不存在,这个OR语法/逻辑在Angular.js中是错误的吗?我一直得到TypeError: Cannot read property 'timestamp' of undefined。但我在chrome调试器中验证了其中至少有一个存在,如sseHandler.result.httpPortResult.timestamp

$scope.$watch(function(){ 
      return sseHandler.result.cpuResult.timestamp || 
       sseHandler.result.networkResult.timestamp || 
       sseHandler.result.httpPortResult.timestamp; 
}, function(){ 
    if (sseHandler.result.cpuResult) { 
     console.log("yes"); 
      cpuUpdate(sseHandler.result); 
    } 
    }); 
}]); 

回答

1

它可能只是做$scope.$watchCollection(sseHandler.result, function() { });更容易,但我不知道是否会满足您的需求,因为它会火任何改变sseHandler.result,不只是时间戳。

否则你需要检查属性是否存在,我怀疑你现在的方式是否会在networkResult上发生变化,就好像cpuResult没有改变一样,它会返回这个值,而angular会认为没有任何变化。所以我可能会这样做:

$scope.$watch(function(){ 
     var ret = ''; 
     if (sseHandler.result.cpuResult) 
      ret += sseHandler.result.cpuResult.timestamp; 
     if (sseHandler.result.networkResult) 
      ret += sseHandler.result.networkResult.timestamp; 
     if (sseHandler.result.httpPortResult) 
      ret += sseHandler.result.httpPortResult.timestamp; 
     return ret; 
     }, function() {}); 
+0

+1 to $ watchCollection。我希望Angular.js文档的api集合有更好的索引。 – dman