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
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.