I have hierarchical data:
[ { "children":[ { "children":[...], [...] }, { "children":[...], [...] }, ], [...] } ]
I want to build a tree grid by smoothing this data. I use the following directives:
app.directive('tree', function (hierarchyService, logger, $timeout) { return { scope: { data: '=' }, restrict: 'E', replace: true, template: '<div>' + '<table class="table table-striped table-hover">' + ' <thead>' + ' <tr>' + ' <th class="col-md-6">Account name</th>' + ' </tr>' + ' </thead>' + ' <tbody><tr collection data="data" /></tbody>' + ' </table>' + '</div>' }; }); app.directive('collection', function() { return { restrict: "A", replace: true, scope: { data: '=', depth: '@' }, template: '<member ng-repeat="member in data" member="member" depth="{{depth}}" />', link: function (scope, element, attrs) { scope.depth = parseInt(scope.depth || 0); } } }); app.directive('member', function($compile) { return { restrict: "E", replace: true, scope: { depth: '@', member: '=' }, template: '<tr ng-class="{selected: member.selected}">' + '<td>' + ' <span ng-show="depth > 0" style="width: {{depth * 16}}px; display: inline-block;"></span> {{member.name}}' + '</td>' + '</tr>', link: function (scope, element, attrs) { scope.depth = parseInt(scope.depth || 0); if (angular.isArray(scope.member.children) && scope.member.children.length > 0) { var el = angular.element('<tr collection data="member.children" depth="{{newDepth}}" />'); scope.depth = parseInt(scope.depth || 0); scope.newDepth = scope.depth + 1; $compile(el)(scope);
The problem is that in the collection added from the link method, depth from the parent area is added to newDepth . As a result, depth for level 3 nodes has the value depth="3 2 1 " .
How to disable depth inheritance?
I also noticed that when I change replace to false in the collection and member directives, the depth works as intended, but then the HTML is invalid.
javascript angularjs angularjs-directive hierarchy
Krzysztof
source share