kramer65
kramer65

Reputation: 53933

Raw javascript in ng-if doesn't work?

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?

Upvotes: 0

Views: 165

Answers (2)

Shripal Soni
Shripal Soni

Reputation: 2448

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

Upvotes: 1

Shaishab Roy
Shaishab Roy

Reputation: 16805

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.

Upvotes: 1

Related Questions