AngularJS using ng-repeat to display hierarchical data

So, I tried to create a good way to represent hierarchical data in my application. I created a slide effect for some boot icons, which I use to display some subcategories using AngularJS.

I created (with some help from you stackoverflow-ers!) The following example that works for data like parent and child. i.e. You cannot be a parent and a child at the same time, which is necessary for my real example.

<ul> <li ng-repeat="category in categories" ng-init="isChild = category.category_type == 'child'" ng-show="category.category_show" class="badge-slider"> <span class="badge {{ isChild ? 'badge-c' : 'badge-p' }}" ng-click="isChild || updateResults(category)" ng-bind="category.category_name"> </span> </li> </ul> 

I am trying to figure out what is the best way to change the code so that it can work for the optional parent and child types of category_type. This type of "parent and child" category_type is needed to create a way to view the directory structure.

In the above example, it relies on the boolean value of isChild and the ternary operator, which does not work when we introduce the category "parent and child" category_type.

Does anyone have any ideas?

Here is a link to PLNKR that demonstrates rolling functionality that works for simple parent-child relationships: http://plnkr.co/edit/9CiXW1YAoPj80x6PtBW3

EDIT 1:

I created another PLNKR to handle the three-level nature of hierarchical relationships. It works great, except that it does not display the parent and child elements with the corresponding icon .... http://plnkr.co/edit/YoRI578GHE91t6torCUt

+4
source share
2 answers

Here is how I solved it:

  • Modified categories data structure
  • Created inline angular template in html file
  • Create a new CSS class for parent and child elements

You can view the working plunker

Here is a snapshot of the result: enter image description here

+3
source

Your data structure is currently not hierarchical. I would suggest a structure like this for your list of categories (possibly a better name), where each element in the array has an array of "children" as a property.

 $scope.categories = [ {category_name:"apples", children: [ {category_name:"bramble", children: [ {category_name:"red"}, {category_name:"green"} ]}, {category_name:"granny smiths"}, {category_name:"pink lady"} ]}, {category_name:"oranges", children: [ {category_name:"satsuma"}, {category_name:"nectarine"}, {category_name:"mandarin"} ]} ]; 

Here is a plunkr ineffective way of representing this (templates and directives would be a more efficient way of dealing with the recursive aspect versus doing it manually).

0
source

All Articles