Submenu (extended / collapsed tree) in AngularJS

Last day I got stuck looking for the best way to use angular to manage a list of menus with submenus.

With jQuery, you can simply listen after the click event for a specific type of element, such as <li> , and add a class to its child to open the menu.

I am trying to do the same as the menu on this page http://geedmo.com/themeforest/wintermin/dashboard.html , with Angular. But you cannot find the right path using my own directive or existing ones like ng-hide and ng-show.

If anyone has an example guide on how to do it best, my day will be saved. :)

I am also new to angular, so I learn a new thing every day.

+6
source share
1 answer

You can use the following code to create an expanded / collapsed submenu in AngularJS.

I have added JSFiddle for you.

 <div ng-controller="MyCtrl"> <ul> <li ng-repeat="item in items" ng-click="showChilds(item)"> <span>{{item.name}}</span> <ul> <li ng-repeat="subItem in item.subItems" ng-show="item.active"> <span>---{{subItem.name}}</span> </li> </ul> </li> </ul> </div> 

Your JS controller:

 function MyCtrl($scope) { $scope.showChilds = function(item){ item.active = !item.active; }; $scope.items = [ { name: "Item1", subItems: [ {name: "SubItem1"}, {name: "SubItem2"} ] }, { name: "Item2", subItems: [ {name: "SubItem3"}, {name: "SubItem4"}, {name: "SubItem5"} ] }, { name: "Item3", subItems: [ {name: "SubItem6"} ] } ]; }; 

UPDATE:

I updated my post because of your comment that when we click on a new menu item, the previous one should be collapsed.

Minor changes in the code.

New JSFiddle with your needs.

 <div ng-controller="MyCtrl"> <ul> <li ng-repeat="item in items" ng-click="showChilds($index)"> <span>{{item.name}}</span> <ul> <li ng-repeat="subItem in item.subItems" ng-show="item.active"> <span>---{{subItem.name}}</span> </li> </ul> </li> </ul> </div> 

You are a JS controller:

 function MyCtrl($scope) { $scope.showChilds = function(index){ $scope.items[index].active = !$scope.items[index].active; collapseAnother(index); }; var collapseAnother = function(index){ for(var i=0; i<$scope.items.length; i++){ if(i!=index){ $scope.items[i].active = false; } } }; $scope.items = [ // items array the same with the previous example ]; }; 
+8
source

Source: https://habr.com/ru/post/977230/


All Articles