Check if an object has a property
73,474
Solution 1
You could use 'hasOwnProperty' to check if object have the specific property.
if($scope.test.hasOwnProperty('bye')){
// do this
}else{
// do this then
}
Here's a demo in jsFiddle.
Hope this helpful.
Solution 2
if('bye' in $scope.test) {}
else {}
Solution 3
The problem is that you probably will have value not just when linking your directive - it could be loaded by $http for example.
My advice would be:
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
});
}
or if you know that the value is assigned only one:
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();
});
}
This code will remove watcher the value of 'test.hello' was assigned (from any controller, ajax, etc etc)
Author by
Daniel R
Updated on February 08, 2020Comments
-
Daniel R over 4 years
How can I check if an object has a certain property in AngularJS?
-
Virendra Singh Rathore over 7 yearsIf you don't know the name of property then you can simply check Object.keys(objName).length. I hope this helps.
-
-
Daniel R over 10 yearsi pass object through directive (with '=') and in my directives controller I have this code snippet for initialization but I get TypeError: Cannot call method 'hasOwnProperty' of undefined. do you know why?
-
Felix Kling over 10 years@user2985439: It sounds like your object does not have a property
test
. -
Chickenrice over 10 years@user2985439 As Felix Kling mentioned, the object your directive referenced doesn't have 'test' property. Could you update your question for more details?
-
Daniel R over 10 yearsscope: {test:'='},controller($scope) {if($scope.test.hasOwnProperty('bye')) {// do stuff}} this returns the type error. I know test is defined because I pass it right through in the view...
-
Daniel R over 10 yearsOk i updated my question.
-
Chickenrice over 10 yearsDoes the blash directive in the controller scope ? My blash directive just work as expected. demo
-
Virendra Singh Rathore over 7 yearsSuppose if i have an object whose keys are leveled let's assume obj.key1.key2.key3 then how can i check key3 exist in obj in one call.