Check if an object has a property [duplicate] Check if an object has a property [duplicate] angularjs angularjs

Check if an object has a property [duplicate]


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.


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


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)