angularJs中基于模板递归的实现

同样的原理,可以通过组合angularJs内置的ng-includeng-init来达到递归的效果,示例模板如下:

复制
 
  1. <script id="recursion" type="text/ng-template">
  2. <li ng-repeat="item in cate">
  3. <a href="{{item.cateId}}">{{item.cateName}}</a>
  4. <ul ng-if="item.child.length" ng-include="'recursion'" ng-init="cate=item.child"></ul>
  5. </li>
  6. </script>

调用方式如下:

复制
 
  1. <div ng-app="demo">
  2. <div ng-controller="demo">
  3. <ul ng-include="'recursion'"></ul>
  4. </div>
  5. </div>

实现效果演示DEMO,"AngularJ基于模板递归实现分类展示"

基于指令递归的实现

同样的道理,在指令中,咱们可以这么来干(内容参考自angular-recursion):

复制
 
  1. angular.module('demo').directive('recursion',function($compile){
  2.  
  3. function cpl(element, link){
  4. // Normalize the link parameter
  5. if(angular.isFunction(link)){
  6. link = { post: link };
  7. }
  8.  
  9. // Break the recursion loop by removing the contents
  10. var contents = element.contents().remove();
  11. var compiledContents;
  12. return {
  13. pre: (link && link.pre) ? link.pre : null,
  14. /**
  15. * Compiles and re-adds the contents
  16. */
  17. post: function(scope, element){
  18. // Compile the contents
  19. if(!compiledContents){
  20. compiledContents = $compile(contents);
  21. }
  22. // Re-add the compiled contents to the element
  23. compiledContents(scope, function(clone){
  24. element.append(clone);
  25. });
  26.  
  27. // Call the post-linking function, if any
  28. if(link && link.post){
  29. link.post.apply(null, arguments);
  30. }
  31. }
  32. };
  33. }
  34. return {
  35. restrict:'A',
  36. scope: {recursion:'='},
  37. template: '<li ng-repeat="item in recursion">\
  38. <a href="{{item.cateId}}.html">{{item.cateName}}</a>\
  39. <ul recursion="item.child">\
  40. </ul>\
  41. </li>',
  42. compile: function(element){
  43.  
  44. return cpl(element, function(scope, iElement, iAttrs, controller, transcludeFn){
  45. // Define your normal link function here.
  46. // Alternative: instead of passing a function,
  47. // you can also pass an object with
  48. // a 'pre'- and 'post'-link function.
  49. });
  50. }
  51. };
  52. });

关于recursion指令

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值