Angular 递归指令

最近需要写一个指令调用自己,就是指令递归,用ng-include不断的ng-include自己实现了,后来在网上发现了更好的方法,偷过来看一下。
1. html模板

<div>
  <div ng-controller="mainCtrl as vm">
    <recurv tree="vm.tree"></recurv>
    <recurv depth="2" tree="vm.tree"></recurv>
    <recurv depth="3" tree="vm.tree"></recurv>
    <recurv depth="4" tree="vm.tree"></recurv>
  </div>
</div>

2.js文件

angular.element(document).ready(function() {
  angular.module('mainApp', [])
    .controller('mainCtrl', mainCtrl)
    .directive('recurv', recurveDirective);

  angular.bootstrap(document, ['mainApp']);

  function mainCtrl() {
    this.name = "Hello";
    this.tree = [{
      title: '1',
      sub: 'coffee'
    }, {
      title: '2',
      sub: 'milk'
    }, {
      title: '3',
      sub: 'tea',
      children: [{
        title: '3.1',
        sub: 'green tea',
        children: [{
          title: '3.1.1',
          sub: 'green coffee',
          children: [{
            title: '3.1.1.1',
            sub: 'green milk',
            children: [{
              title: '3.1.1.1.1',
              sub: 'green tea tea'
            }]
          }]
        }]
      }]
    }]
  }

  function recurveDirective() {
    var ctr = 0,
      depth = null;
    return {
      template: '<ul><li ng-repeat="t in tree">{{t.sub}}<recurv tree="t.children"></recurv></li></ul>',
      scope: {
        tree: '='
      },
      compile: function(tElement, tAttrs) {
        depth = tAttrs.depth || depth || 1;
        if (ctr == depth) {
          tElement.find('recurv').remove();
          depth = 'end';
        }
        depth == 'end' ? ctr = 0 : ctr++;
      },
    }
  }

});

depth控制深度。

参考: https://jsfiddle.net/cattails27/5j5au76c/
stackoverflow: https://stackoverflow.com/questions/14430655/recursion-in-angular-directives

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值