Directive to iterate on complex JSON structure

Hi Guys,

You can find how to create directive in order to iterate over a complex JSON structure.

In the code below I have implemented directive which handle this.
Let me get to the code how you can use this directive.

Its start with html.
You have to add two lines of code
<ng-treeview ng-model="jsonObj"></ng-treeview>
<div id="tree"></div>
1. ng-treeview is a directive which has scope model that contains JSON which user can pass dynamically.
2. It is a placeholder where we display tree view.

Now coming to its implementation. I have added a controller which has a variable $scope.jsonObj hold JSON data. And this is passed to directive in-order to iterate and generate treeview.

Coming to the directive, it has scope ngModel and is restricted to Element only. The logic to treeview is in link function which is called on page load.

You can find implementation code below.

index.html
<html ng-app="simpleDirective">
<head>
<script src="angular.min.js"></script>
<script src="jquery.js"></script>
<script src="app.js"></script>
<style>
ul{
 list-style:none
}
ul li{
 border-bottom:1px solid lightgrey
}
</style>
</head>
<body style="margin:10;padding:0;">
<div style="margin:0 auto" ng-controller="Controller">
<h2>Original Json</h2>
<div style="border:1px solid lightgrey; padding:10px;margin-bottom:20px">
{{jsonObj}}
</div>
<h2>AngularJS directive to iterate on json</h2>
<div style="border:1px solid lightgrey; padding:10px;margin-bottom:20px">
<ng-treeview ng-model="jsonObj"></ng-treeview>
<div id="tree"></div>
</div>
</div>
</body>
</html>
app.js
var app = angular.module('simpleDirective', []);
app.controller('Controller', ['$scope', function($scope) {
 $scope.jsonObj = {
  first:"1",
  second:{
   third:"3"
  },
  fourth:[{
   fifth:"5"
  },{
   sixth:{
    seventh:"7"
   }
  }],
  eighth:"8"
 };
}]);

app.directive("ngTreeview", function(){
 return{
  restrict:"E",
scope:{
ngModel:"="
},
  link:function($scope){
   var treeStructure = "<ul>";
   
   $scope.treeView = function(objList){
    for(var obj in objList){
     if(angular.isArray(objList[obj])){
      treeStructure += "
<li>"+obj+"</li>
";
      treeStructure += "<ul>"; 
      $scope.treeView(objList[obj]);
     }else if(angular.isObject(objList[obj])){
      console.log(obj+" : "+isNaN(obj));
      if(isNaN(obj)==true){
       treeStructure += "
<li>"+obj+"</li>
";  
      }
      treeStructure += "<ul>"; 
      $scope.treeView(objList[obj]);
     }else{
      treeStructure += "
<li>"+obj+":"+objList[obj]+"</li>
";
     }     
    }
    treeStructure += "</ul>
" ;
   }
   $scope.treeView($scope.ngModel);
   $("#tree").append(treeStructure);
  }
 }
});


Plunkr: https://plnkr.co/edit/V3Kg4KQ2M624lKfFfqEt?p=preview

Good Day :)

Post a Comment

0 Comments