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)

Share:
73,474
Daniel R
Author by

Daniel R

Updated on February 08, 2020

Comments

  • Daniel R
    Daniel R over 4 years

    How can I check if an object has a certain property in AngularJS?

    • Virendra Singh Rathore
      Virendra Singh Rathore over 7 years
      If you don't know the name of property then you can simply check Object.keys(objName).length. I hope this helps.
  • Daniel R
    Daniel R over 10 years
    i 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
    Felix Kling over 10 years
    @user2985439: It sounds like your object does not have a property test.
  • Chickenrice
    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
    Daniel R over 10 years
    scope: {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
    Daniel R over 10 years
    Ok i updated my question.
  • Chickenrice
    Chickenrice over 10 years
    Does the blash directive in the controller scope ? My blash directive just work as expected. demo
  • Virendra Singh Rathore
    Virendra Singh Rathore over 7 years
    Suppose 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.