栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JavaScript Angular指令中的递归

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript Angular指令中的递归

线程中描述的解决方案的启发,我将递归功能抽象为service。

module.factory('RecursionHelper', ['$compile', function($compile){    return {                compile: function(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,          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);         }     } };        }    };}]);

用法如下:

module.directive("tree", ["RecursionHelper", function(RecursionHelper) {    return {        restrict: "E",        scope: {family: '='},        template:  '<p>{{ family.name }}</p>'+ '<ul>' +      '<li ng-repeat="child in family.children">' +          '<tree family="child"></tree>' +     '</li>' + '</ul>',        compile: function(element) { // Use the compile function from the RecursionHelper, // And return the linking function(s) which it returns return RecursionHelper.compile(element);        }    };}]);

观看此Plunker进行演示。我最喜欢此解决方案,因为:

  1. 您不需要特殊的指令,这会使您的html不太干净。
  2. 递归逻辑被抽象到RecursionHelper服务中,因此您可以保持指令整洁。

更新:从Angular 1.5.x开始,不再需要其他技巧,但仅适用于 template ,不适用于 templateUrl



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/456693.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号