AngularJS中的递归菜单

时间:2015-02-07 13:16:52

标签: javascript angularjs recursion angularjs-ng-repeat angular-ui-bootstrap

我是AngularJS的新手。我想用多个级别构建一个ListView类型的菜单。我在网上找到的大多数例子都是开发树形结构。我想要的是一次显示一个级别。我已经选择了下面给出的现有示例(请参阅此JSFiddle):

这是我的HTML:

<div ng-app="app" ng-controller='AppCtrl'>
    <script type="text/ng-template" id="categoryTree">
        {{ category.title }}
        <ul ng-if="category.categories">
            <li ng-repeat="category in category.categories" ng-include="'categoryTree'" ng-click="DisplayNextLevel($index)">           
            </li>
        </ul>
    </script>
    <ul>
        <li ng-repeat="category in categories" ng-include="'categoryTree'"></li>
    </ul>    
</div>

这是我的JS:

var app = angular.module('app', []);

app.controller('AppCtrl', function ($scope) {

    // Do something to display next Menu Level
    $scope.DisplayNextLevel = function(Index) {
        $window.alert('Alert!');
        $window.alert(Index);
    };


$scope.categories = [
  { 
    title: 'Computers',
    categories: [
      {
        title: 'Laptops',
        categories: [
          {
            title: 'Ultrabooks'
          },
          {
            title: 'Macbooks'            
          }
        ]
      },

      {
        title: 'Desktops'
      },

      {
        title: 'Tablets',
        categories: [
          { 
            title: 'Apple'
          },
          {
            title: 'Android'
          }
        ]        
      }
    ]
  },

  {
    title: 'Printers'
  }

];

});

我希望程序在启动时只显示第一级项目,即:

o Computers
o Printers

当用户点击计算机时,它应显示下一级计算机​​,同时删除第一级,即:

Laptops
Desktops
Tablets

依旧......

如何修改DisplayNextLevel()或任何其他方法来实现此目标?

1 个答案:

答案 0 :(得分:1)

您必须有单独的变量 - currentLevel和parentLevl

http://plnkr.co/edit/rNbEMoC3OrG7YMbl9aFW?p=preview

$scope.displayNextLevel = function(i) {
  $scope.parentLevel = $scope.currentLevel[i];
  $scope.currentLevel = $scope.currentLevel[i].categories;
}