Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
34
rated 0 times [  41] [ 7]  / answers: 1 / hits: 22364  / 10 Years ago, sun, october 26, 2014, 12:00:00

I have for the past day got stuck on finding the best way to use angular to control a menu list with sub-menus.



With jQuery you can just listen after a click event on a specific type of element like a <li> and add a class to its child element for a menu to open.



I'm trying to do the same thing like the menu on this page http://geedmo.com/themeforest/wintermin/dashboard.html, with Angular. But can't find the correct way by using my own directive or existing ones like ng-hide and ng-show.



If anyone have an example og guides on how to do this the best way, my day would be saved. :)



I'm also new to angular so learning new thing every day.


More From » html

 Answers
15

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



I've attached JSFiddle example 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've updated my post due to your comment about, that when we click on the new menu's item, the previous should be collapsed.



Small changes in the code.



New JSFiddle with your need.



<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 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
];
};

[#69012] Wednesday, October 22, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kieraelsies

Total Points: 718
Total Questions: 103
Total Answers: 104

Location: England
Member since Sun, May 21, 2023
1 Year ago
kieraelsies questions
Tue, Aug 3, 21, 00:00, 3 Years ago
Tue, Feb 23, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Mon, Sep 16, 19, 00:00, 5 Years ago
;