AngularJS中的子菜单(展开/折叠树)

Ben*_*ent 6 html javascript angularjs angular-ui angularjs-directive

在过去的一天里,我一直坚持找到使用angular来控制带有子菜单的菜单列表的最佳方法.

使用jQuery,您可以在特定类型的元素(例如a)上单击事件后进行侦听,<li>并在其子元素中添加一个类以打开菜单.

我正在尝试使用Angular 这个页面上的菜单http://geedmo.com/themeforest/wintermin/dashboard.html做同样的事情.但无法通过使用我自己的指令或现有的指令(如ng-hide和ng-show)找到正确的方法.

如果有人有一个示例og指南如何以最好的方式做到这一点,我的日子将被保存.:)

我也很有新意,所以每天都要学习新东西.

Art*_*ich 8

您可以使用以下代码在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>
Run Code Online (Sandbox Code Playgroud)

你的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"}
            ]
        }
    ];
};
Run Code Online (Sandbox Code Playgroud)

更新:

由于您的评论我已经更新了我的帖子,当我们点击新菜单的项目时,前一个应该折叠.

代码中的小变化.

新的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>
Run Code Online (Sandbox Code Playgroud)

你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
    ];
};
Run Code Online (Sandbox Code Playgroud)