greedz greedz - 3 months ago 20
AngularJS Question

How can I check in an angular view if an object's property is an object itself?

I'm building some form views with angular and need to run over some nested objects.

I've run into an issue and can't figure out exactly what I'm missing.

<div ng-app="app">

<div ng-controller="Main">

<div ng-repeat="(key, value) in ob">
{{key}}
<div ng-if="angular.isObject(ob[key])">
angular.isObject() returns true!
</div>
<div ng-if="!angular.isObject(ob[key])">
angular.isObject() returns false!
</div>

<div ng-if="typeof(ob[key]) === 'object'">
typeof is object!
</div>

<div ng-if="typeof(ob[key]) !== 'object'">
typeof is not object!
</div>

</div>

</div>

</div>


In controller:

$scope.ob = {
prop1: 1,
prop2: 'asd',
prop3: {
subprop1: 'one',
subprop2: 'two'
}
};


In the code above I'm trying to use
angular.isObject
to detect whether the property is an object, so I can go into another loop afterwards. Both ng-ifs resolve to false, even if my third property is an object. Same while using
typeof
.

Codepen link: http://codepen.io/anon/pen/rLEVLr

Answer

You can't use angular in template. Template is evaluated against scope object, not global one (e.g. window, which has angular property as global variable).

If you really want to you can simply expose reference to the angular like this:

$scope.angular = angular

Demo: http://codepen.io/anon/pen/yJdNzV?editors=1010

But better approach is to expose only function that you actually need:

$scope.isObject = angular.isObject

and use it in template like this:

ng-if="isObject(value)"