javascript - AngularJS 中的子菜單(展開/折疊樹狀)
在過去的一天裡,我一直卡在如何使用 Angular 來控制帶有子選單的選單列表的最佳方法上。
使用 jQuery,你可以在特定類型的元素(例如 <li>)上監聽點擊事件,並為其子元素添加一個類,以便打開菜單。
我正在嘗試用 Angular 做同這個頁面上的菜單一樣的功能 http://geedmo.com/themeforest/wintermin/dashboard.html。但無法找到使用我自己的指令或像 ng-hide 和 ng-show 這樣的現有指令的正確方法。
如果有人有關於如何以最佳方式做這件事的指南範例,我的今天就能被拯救。:)
我也是 Angular 新手,所以每天都在學習新東西。
答案#1
你可以使用以下程式碼在 AngularJS 上建立展開/收起的子選單。
我已為你附上 JSFiddle 範例。
<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>
你的 JS 控制器:
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"}
]
}
];
};
更新:
由於你關於當我們點擊新菜單項目時,之前的應該收起來的評論,我已經更新了我的帖子。
程式碼的小變動。
使用您需要的功能建立新的 JSFiddle。
<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>
你的 JS 控制器:
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
];
};
