Aman Kumar
Aman Kumar

Reputation: 232

Using ng-if to check angular variable from another directive in angularjs

I am new to angular. I have a task to display json data in specific design, but I have not idea about nesting of json. Is it possible to check if the data is json or an array of json and then display the output.

Here I am trying to display data only if it is an array. But it is not working. Kindly help.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp">

<div ng-controller="readJson as rj">


<div ng-repeat="d in rj.data">
<ul>
<div ng-model="myVar" ng-init="myVar = "{{isArray(d.third)}}>
<div ng-if="myVar">
<li>{{d.third}}</li>

</div>
</ul>
</div>
</div>


</div>

</body>
<script>
(function(){
var app=angular.module('myApp',[]);

app.controller('readJson',function($scope){
 $scope.isArray = angular.isArray;
this.data=[{"first":"one","second":"two","third":"three"},
{"first":"ONE","second":"two","third":"three"},
{"first":"onE","second":"two","third":
[
{"first":"1one","second":"2two","third":"3three"},
{"first":"1ONE","second":"2two","third":"3three"}
]}];

});
})();
</script>

</html>

Upvotes: 2

Views: 116

Answers (1)

kodu.cloud
kodu.cloud

Reputation: 1600

Here you go. This example will display data only when "third" param is an array. https://plnkr.co/edit/EX0BvcYrLPFbiN2ezlqQ

<div ng-repeat="d in data">
    <ul>
        <div ng-init="myVar = isArray(d.third)"></div>
        <div ng-if="myVar">
            <li>{{d.third}}</li>
        </div>
    </ul>
</div>

The problem was in ng-init="myVar = "{{isArray(d.third)}} - you need to make sure isArray(d.third) is in expression (between "") and there is no need to use {{}} syntax within ng-init directive. It will evaluate expression for you (check an example).

Upvotes: 2

Related Questions