Angular 递归指令

xiaoxiao2021-02-28  92

最近需要写一个指令调用自己,就是指令递归,用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

转载请注明原文地址: https://www.6miu.com/read-30184.html

最新回复(0)