【发布时间】:2013-12-26 05:15:24
【问题描述】:
如何在 AngularJS 中检查对象是否具有特定属性?
【问题讨论】:
-
如果您不知道属性的名称,那么您可以简单地检查 Object.keys(objName).length。我希望这会有所帮助。
如何在 AngularJS 中检查对象是否具有特定属性?
【问题讨论】:
您可以使用 'hasOwnProperty' 来检查对象是否具有特定的 属性。
if($scope.test.hasOwnProperty('bye')){
// do this
}else{
// do this then
}
这是 jsFiddle 中的 demo。
希望这有帮助。
【讨论】:
test的属性。
if('bye' in $scope.test) {}
else {}
【讨论】:
问题在于,您可能不仅在链接指令时会有价值 - 例如,它可以由 $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 等)
【讨论】: