1

I have some sample data in JSON format:

{
  "menus" : [
    {"name" : "Item 1", "children" : [
      {"name" : "Item 1.1", "url" : "http://www.website.com1/1"},
      {"name" : "Item 1.2", "url" : "http://www.website.com1/2"},
      {"name" : "Item 1.3", "children": [
        {"name" : "Item 1.3.1", "url" : "http://www.website.com1/3/1"},
        {"name" : "Item 1.3.2", "url" : "http://www.website.com1/3/2"},
        {"name" : "Item 1.3.3", "url" : "http://www.website.com1/3/3"}
      ]}
    ]},
    {"name" : "Item 2", "children": [
      {"name" : "Item 2.1", "url" : "http://www.website.com2/1"},
      {"name" : "Item 2.2", "url" : "http://www.website.com2/2"},
      {"name" : "Item 2.3", "url" : "http://www.website.com2/3"}
    ]},
    {"name" : "Item 3", "url" : "http://www.website.com3"}
  ]
}

I want to build a menu tree that matches the stucture of the JSON. So I made a directive:

app.directive('menuItem',
function(){
    return {
        restrict : "E",
        scope: { data : '='},
        replace:true,
        templateUrl: 'directives/menu-item.html'
    };  
});

I add the directive to my HTML and it works great for the first layer:

<menu-item data="menu.data.menus"></menu-item>

What I want to happen is that if model the directive is using has a 'children' property, I want it to build a new node using the same template as itself:

<ul class="menu-items" ng-repeat="item in data">
    <li class="menu-item">
        <div>{{item.name}}</div>
        <div ng-if="item.children.length">
                    <!-- when I add this line I get problems -->
            <menu-item data="item.children"></menu-item>
        </div>
    </li>
</ul>

I get the following error:

Error: [$rootScope:inprog] http://errors.angularjs.org/1.3.0-beta.13/$rootScope/inprog?p0=%24digest

Question is, how can I get the desired functionality, and how should I think about what's going on to understand this better?

Fiddle to come...

Thierry Blais
  • 2,848
  • 22
  • 41
  • 2
    possible duplicate: http://stackoverflow.com/questions/11854514/is-it-possible-to-make-a-tree-view-with-angular – Jonathan Wilson Jun 30 '14 at 00:25
  • 6
    possible duplicate of [How to handle recursive rendering of data using AngularJS](http://stackoverflow.com/questions/18415142/how-to-handle-recursive-rendering-of-data-using-angularjs) – vittore Jun 30 '14 at 00:25

1 Answers1

1

Ok Thanks. Yes this was in fact the same issue adressed in How to handle recursive rendering of data using AngularJS

For this particular case, it would be important to mention that in it's present formulation the template would need to use "ng-init" to properly recurse.

<ul class="menu-items" ng-repeat="item in data">
    <li class="menu-item">
        <div>{{item.name}}</div>
        <div ng-include="'directives/menu-item.html'" ng-init="data = item.children" class="submenu-item"></div>
    </li>
</ul>
Community
  • 1
  • 1
Thierry Blais
  • 2,848
  • 22
  • 41