检查对象是否具有属性

时间:2013-12-09 06:51:41

标签: angularjs object

如何检查对象在AngularJS中是否具有某个属性?

3 个答案:

答案 0 :(得分:34)

  

您可以使用' hasOwnProperty '来检查对象是否具有特定对象   属性。

if($scope.test.hasOwnProperty('bye')){
  // do this   
}else{
  // do this then
}

这是jsFiddle中的demo

希望这有用。

答案 1 :(得分:2)

if('bye' in $scope.test) {}
else {}

答案 2 :(得分:1)

问题是你可能不仅在链接你的指令时有价值 - 例如它可以用$ http加载。

我的建议是:

controller: function($scope) {
  $scope.$watch('test.hello', function(nv){ 
     if (!nv) return; 
     // nv has the value of test.hello. You can do whatever you want and this code
     // would be called each time value of 'hello' change
  });
}

或者如果您知道该值只分配了一个:

controller: function($scope) {
  var removeWatcher = $scope.$watch('test.hello', function(nv){ 
     if (!nv) return; 
     // nv has the value of test.hello. You can do whatever you want
     removeWatcher();
  });
}

此代码将删除观察者已分配'test.hello'的值(来自任何控制器,ajax等)