简体   繁体   English

如何使用$ templateCache进行递归指令?

[英]How to do recursive directive with $templateCache?

I was trying to use angular.treeview to display a tree structure, and it works just fine. 我试图使用angular.treeview来显示树形结构,并且效果很好。 However, it causes infinite loop when I use $templateCache to make it more maintainable. 但是,当我使用$ templateCache使其更具可维护性时,它将导致无限循环。 It looks like using a string to store the template removes the outermost loop in the recursive calls that is not happening with template retrieved from $templateCache. 看起来,使用字符串存储模板可以消除递归调用中最外面的循环,而从$ templateCache检索到的模板则不会发生这种情况。 You will see the problem after commenting out the second line (line #88 in angular.treeview.js) in my example at http://plnkr.co/edit/khQ7BMPRYedK6B1PVlDY?p=preview . 在我的示例中,注释掉第二行(angular.treeview.js中的第88行)后,您会看到问题, 网址http://plnkr.co/edit/khQ7BMPRYedK6B1PVlDY?p=preview

$log.log('cache:' + templateCache.get('treeNode.html'));
//template = templateCache.get('treeNode.html
$log.log('string:' + template);
                    //Rendering template.
                    element.html('').append( $compile( template )( scope ) );

The other question if I can get $templateCache work is how to replace variables in the template before it's compiled? 我能否使$ templateCache工作的另一个问题是如何在编译模板之前替换模板中的变量? I'd like to replace those variables like treeModel and nodeChildren in the template to make the code more flexible. 我想在模板中替换诸如treeModel和nodeChildren之类的变量,以使代码更灵活。

Got it working by naming controller's $scope variable same as the recursive call's. 通过命名控制器的$ scope变量与递归调用的变量相同来使其工作。 In other words, change $scope.roleList to $scope.node.children solved the infinite loop problem. 换句话说,将$ scope.roleList更改为$ scope.node.children可解决无限循环问题。

//template refrence node.children
<li data-ng-repeat="node in node.children">

//assign tree nodes to $scope.node.children
$scope.node = {};
$scope.node.children = this.roleList1;

Since I have moved to using controllerAs syntax, I created an example at http://plnkr.co/edit/Ua63IlaAqsRtgiGfbMaq?p=preview with the fix, and the mix of using $scope and controllerAs variables. 由于我已经开始使用controllerAs语法,因此在http://plnkr.co/edit/Ua63IlaAqsRtgiGfbMaq?p=preview中创建了一个示例,并附带了修复程序以及$ scope和controllerAs变量的混合使用。 The fix essentially utilize the side-effect of referencing $scope variables without qualifying with $scope. 该修复程序实质上利用了引用$ scope变量而不用$ scope限定的副作用 , so you can use the same name to refer to your $scope variables as well as the local variables inside the recursive loop. ,因此您可以使用相同的名称来引用$ scope变量以及递归循环中的局部变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM