Javascript 角域中的递归
编辑:刚刚遇到这么一个帖子。它最好地回答了我的问题Javascript 角域中的递归,javascript,angularjs,recursion,Javascript,Angularjs,Recursion,编辑:刚刚遇到这么一个帖子。它最好地回答了我的问题 您将如何递归/更好地实现以下功能: HTML <div ng-controller='MainController as vm'> <div ng-repeat='tango in vm.tangos'> <p>{{ tango.text }}</p> <div ng-repeat='subtango in tango.children'> <p
您将如何递归/更好地实现以下功能: HTML
<div ng-controller='MainController as vm'>
<div ng-repeat='tango in vm.tangos'>
<p>{{ tango.text }}</p>
<div ng-repeat='subtango in tango.children'>
<p>{{ subtango.text }}</p>
<div ng-repeat='subsubtango in subtango.children'>
<p>{{ subsubtango.text }}</p>
<!-- ... -->
</div>
</div>
</div>
</div>
<div ng-controller='MainController as vm'>
<div ng-repeat='tango in vm.tangos'>
<tango tango='tango'></tango>
</div>
</div>
使用指令似乎不起作用():
HTML
<div ng-controller='MainController as vm'>
<div ng-repeat='tango in vm.tangos'>
<p>{{ tango.text }}</p>
<div ng-repeat='subtango in tango.children'>
<p>{{ subtango.text }}</p>
<div ng-repeat='subsubtango in subtango.children'>
<p>{{ subsubtango.text }}</p>
<!-- ... -->
</div>
</div>
</div>
</div>
<div ng-controller='MainController as vm'>
<div ng-repeat='tango in vm.tangos'>
<tango tango='tango'></tango>
</div>
</div>
即使tango.children
为空,我也假设它正在实例化指令(可能不是正确的单词)。如果是这样,我不确定如何防止这种情况。请查看此演示:
定义模板并使用$compile
执行以下操作:
.directive('item', ['$compile', function( $compile ) {
var itemTemplate =
'<div>{{ text }} # of children: {{children.length}}</p>' +
'<div ng-show="children.length > 0">' +
'<div ng-repeat="i in children">' +
'<div item children="i.children" text="{{i.text}}">{{ i | json }}</div>' +
'</div>' +
'</div>' +
'</div>';
return {
restrict: 'AE',
scope: {
children: '=',
text: '@'
},
// template: itemTemplate
link: function (scope, element) {
element.html('').append( $compile( itemTemplate )( scope ) );
}
}
}]);
.directive('item',['$compile',function($compile){
var itemTemplate=
儿童的{{text}}}{{{children.length}}'+
'' +
'' +
“{i|json}”+
'' +
'' +
'';
返回{
限制:“AE”,
范围:{
儿童:“=”,
正文:“@”
},
//模板:itemTemplate
链接:功能(范围、元素){
html(“”).append($compile(itemTemplate)(scope));
}
}
}]);
像树一样,对吧?@Joy sigh。。。它可以很好地作为树结构工作,但不能在链接结构上重复,只能在数组上重复。你可以在函数的输出上重复。函数遍历树并以所需的顺序返回数组。你知道为什么这样工作,但我的tango
指令导致无限递归吗?此外,是否可以使用您的方法,但可以从html文件获取模板(因此更易于维护)?如果您想将其放入模板文件中,以供参考:和。它们都使用字符串模板,而不是从外部html文件获取模板。这是:
.directive('item', ['$compile', function( $compile ) {
var itemTemplate =
'<div>{{ text }} # of children: {{children.length}}</p>' +
'<div ng-show="children.length > 0">' +
'<div ng-repeat="i in children">' +
'<div item children="i.children" text="{{i.text}}">{{ i | json }}</div>' +
'</div>' +
'</div>' +
'</div>';
return {
restrict: 'AE',
scope: {
children: '=',
text: '@'
},
// template: itemTemplate
link: function (scope, element) {
element.html('').append( $compile( itemTemplate )( scope ) );
}
}
}]);