0

I'm trying to check if a key exists in an object in an Angular $scope. In my controller I've got this:

$scope.the_object = {'the_key': 123};

And in my template I've got this:

<span ng-if="'the_key' in the_object">
    the_key exists in the_object
</span>

but I get the following trace in the console:

Error: [$parse:syntax] http://errors.angularjs.org/1.4.7/$parse/syntax?p0=in&p1=is%20an%20unexpected%20token&p2=11&p3='the_key'NaNn%20the_object&p4=in%20the_object
    at Error (native)
    at http://52.29.xx.xx:5000/bower/angular/angular.min.js?version=1.4.7:6:416
    at Object.s.throwError (http://52.29.xx.xx:5000/bower/angular/angular.min.js?version=1.4.7:209:339)
    at Object.s.ast (http://52.29.xx.xx:5000/bower/angular/angular.min.js?version=1.4.7:202:118)
    at Object.sd.compile (http://52.29.xx.xx:5000/bower/angular/angular.min.js?version=1.4.7:211:203)
    at fc.parse (http://52.29.xx.xx:5000/bower/angular/angular.min.js?version=1.4.7:238:193)
    at b.$get (http://52.29.xx.xx:5000/bower/angular/angular.min.js?version=1.4.7:117:315)
    at n.a.$get.n.$watch (http://52.29.xx.xx:5000/bower/angular/angular.min.js?version=1.4.7:127:125)
    at a.link (http://52.29.xx.xx:5000/bower/angular/angular.min.js?version=1.4.7:254:214)
    at aa (http://52.29.xx.xx:5000/bower/angular/angular.min.js?version=1.4.7:73:90)

Any how I can check if the_key exists in the_object from within the ng-if?

kramer65
  • 50,427
  • 120
  • 308
  • 488

2 Answers2

1

If the property you want to check is inside your object and not the inherited one, you can use below code.

<span ng-if="the_object.hasOwnProperty('the_key')"> the_key exists in the_object </span>

If above is not the case and you make sure that you don't initalize the_key undefined in your object, you can use below code:

<span ng-if="the_object['the_key'] !== undefined"> the_key exists in the_object </span>

check this plunker

If you make sure, you don't initialize any value of your object undefined, the second approach is way faster than the first one. Check more about this at https://stackoverflow.com/a/22074727/3292746

Community
  • 1
  • 1
Shripal Soni
  • 2,448
  • 17
  • 15
  • It works! But why?! Do you know why the normal javascript I try to use doesn't work? I thought Angular simply takes the code between the quotes and evaluates it as js? – kramer65 Feb 03 '16 at 13:10
  • It is because, ng-if expect angular expression and angular-expression is not same as javascript expression. Know more about Angular Expression at (https://docs.angularjs.org/guide/expression). And as per that it doesn't allow void expressoin.But it works. Its is better to use undefined instead of void(0). – Shripal Soni Feb 03 '16 at 13:25
1

You can simply check

ng-if="the_object.the_key !== undefined"

it check the_key exist or not in the_object. if exist it return true and if not exist it return false. exist means not undefined.

Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68