同样的原理,可以通过组合angularJs内置的ng-include
、ng-init
来达到递归的效果,示例模板如下:
复制
- <script id="recursion" type="text/ng-template">
- <li ng-repeat="item in cate">
- <a href="{{item.cateId}}">{{item.cateName}}</a>
- <ul ng-if="item.child.length" ng-include="'recursion'" ng-init="cate=item.child"></ul>
- </li>
- </script>
调用方式如下:
复制
- <div ng-app="demo">
- <div ng-controller="demo">
- <ul ng-include="'recursion'"></ul>
- </div>
- </div>
实现效果演示DEMO,"AngularJ基于模板递归实现分类展示"
基于指令递归的实现
同样的道理,在指令中,咱们可以这么来干(内容参考自angular-recursion):
复制
- angular.module('demo').directive('recursion',function($compile){
- function cpl(element, link){
- // Normalize the link parameter
- if(angular.isFunction(link)){
- link = { post: link };
- }
- // Break the recursion loop by removing the contents
- var contents = element.contents().remove();
- var compiledContents;
- return {
- pre: (link && link.pre) ? link.pre : null,
- /**
- * Compiles and re-adds the contents
- */
- post: function(scope, element){
- // Compile the contents
- if(!compiledContents){
- compiledContents = $compile(contents);
- }
- // Re-add the compiled contents to the element
- compiledContents(scope, function(clone){
- element.append(clone);
- });
- // Call the post-linking function, if any
- if(link && link.post){
- link.post.apply(null, arguments);
- }
- }
- };
- }
- return {
- restrict:'A',
- scope: {recursion:'='},
- template: '<li ng-repeat="item in recursion">\
- <a href="{{item.cateId}}.html">{{item.cateName}}</a>\
- <ul recursion="item.child">\
- </ul>\
- </li>',
- compile: function(element){
- return cpl(element, function(scope, iElement, iAttrs, controller, transcludeFn){
- // Define your normal link function here.
- // Alternative: instead of passing a function,
- // you can also pass an object with
- // a 'pre'- and 'post'-link function.
- });
- }
- };
- });