Recursion with ng-repeat in Angular

前端 未结 10 1270
心在旅途
心在旅途 2020-12-15 19:17

I have the following data structure for items in my sidemenu, in an Angular app based on a paid-for web site theme. The data structure is my own, and the menu is derived fro

10条回答
  •  北海茫月
    2020-12-15 19:42

    Recursion can be very tricky. As things will get out of hand depending on how deep your tree is. Here is my suggestion:

    .directive('menuItem', function($compile){
        return {
            restrict: 'A',
            scope: {
                menuItem: '=menuItem'
            },
            templateUrl: 'menuItem.html',
            replace: true,
            link: function(scope, element){
                var watcher = scope.$watch('menuItem.subItems', function(){
                    if(scope.menuItem.subItems && scope.menuItem.subItems.length){
                        var subMenuItems = angular.element('
    ') $compile(subMenuItems)(scope); element.append(subMenuItems); watcher(); } }); } } })

    HTML:

  • {{ menuItem.text }}
  • This will make sure it doesn't create sub items repeatedly. You can see it working in a jsFiddle here: http://jsfiddle.net/gnk8vcrv/

    If you find it's crashing your app because you have a massive amount of lists (I'd be interested to see) you can hide the parts of the if statement besides the watcher behind a $timeout.

提交回复
热议问题