32

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

user229044
  • 232,980
  • 40
  • 330
  • 338
Daniel R
  • 355
  • 1
  • 5
  • 9

3 Answers3

40

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.

Kaleem Elahi
  • 316
  • 2
  • 14
Chickenrice
  • 5,727
  • 2
  • 22
  • 21
  • 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? – Daniel R Dec 09 '13 at 07:48
  • @user2985439: It sounds like your object does not have a property `test`. – Felix Kling Dec 09 '13 at 07:52
  • @user2985439 As Felix Kling mentioned, the object your directive referenced doesn't have 'test' property. Could you update your question for more details? – Chickenrice Dec 09 '13 at 08:01
  • 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 Dec 09 '13 at 08:02
  • Does the blash directive in the controller scope ? My blash directive just work as expected. [demo](http://jsfiddle.net/J83Ch/3/) – Chickenrice Dec 09 '13 at 08:32
  • 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. – Virendra Singh Rathore Dec 07 '16 at 13:03
2
if('bye' in $scope.test) {}
else {}
codebreach
  • 2,155
  • 17
  • 30
1

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)

Valentyn Shybanov
  • 19,331
  • 7
  • 66
  • 59