【发布时间】:2016-04-18 14:30:25
【问题描述】:
我编写了一个 angularjs 服务,它使用下面显示的函数从“平面”数组生成树状数组。 此服务作为控制器的依赖项注入(见下文),并通过服务对象中返回的 get() 方法绑定到范围。
var arr = [
{"id": 1, "firstName": "Macko","parentId": 12},
{"id": 2, "firstName": "Jess","parentId": 1},
{"id": 3, "firstName": "Peter","parentId": 1},
{"id": 4, "firstName": "Lisa", "parentId": 1},
{"id": 5, "firstName": "Megan","parentId": 1},
{"id": 6, "firstName": "John", "parentId": 4},
{"id": 7, "firstName": "Joe", "parentId": 4},
{"id": 8, "firstName": "Matthew","parentId": 2},
{"id": 9, "firstName": "Peter","parentId": 2},
{"id": 10, "firstName": "Dio","parentId": 5},
{"id": 11, "firstName": "Hello","parentId": 5},
{"id": 12, "firstName": "Ana", "parentId": 4}
];
var getNestedChildren = function(arr, id, checked) {
var out = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i].parentId === id && checked.indexOf(arr[i].id) === -1) {
checked.push(id);
var children = getNestedChildren(arr, arr[i].id, checked);
if (children.length) {
arr[i].children = children;
}
out.push(arr[i]);
}
}
return out;
};
return {
get: function (element) {
return getNestedChildren(arr, element.id, []);
}
}
我将此树绑定到控制器中的 $scope,如下所示。在 URL 中传递生成树的参数。
$scope.tree = myService.get({elementId: $routeParams.elementId});
当我几次切换路线以查看不同参数的树时,创建的树每次都有更多元素,直到某个点角度返回错误
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
我的猜测是,因为 myService 是一个单例,它通过路由保留状态,这就是我得到不一致数据的原因。
我怎样才能阻止这种行为?也许在生成特定树后重置服务?
请帮忙。
编辑: 我尝试在离开特定视图的同时清理 $templateCache 和 $scope,但没有效果。到目前为止,只有在切换几条路线后,浏览器刷新才会显示正确的树。
根据请求显示呈现树的 html:
指令
angular.module('app').directive('showTree', [function () {
return {
restrict: 'E',
templateUrl: 'app/tree/tree.tpl.html'
}
}]);
tree.tpl.html:
<h3> {{selectedElement.firstName}} {{selectedElement.lastName}}"></h3>
<ul>
<li ng-repeat="element in tree" ng-include="'tree'"></li>
</ul>
<script type="text/ng-template" id="tree">
<h3> {{element.firstName}} {{element.lastName}}"></h3>
<ul>
<li ng-repeat="element in element.children" ng-include="'tree'"></li>
</ul>
</script>
控制器
angular.module('app')
.controller('TreeController', ['$scope', '$routeParams', 'ElementFactory', 'myService',
function ($scope, $routeParams, ElementFactory, myService) {
$scope.selectedElement = ElementFactory.get({elementId: $routeParams.elementId});
$scope.tree = myService.get({elementId: $routeParams.elementId});
}]);
【问题讨论】:
标签: javascript angularjs recursion tree