angularjs解决方案之 递归模板
手风琴模式的菜单:
在项目中我们会遇到不知层级的json数据,需要前端人员去遍历生成View视图,这种情况下我们就会用到递归方法。
angularjs中的dom结构也是可以用递归的方式去循环遍历数据。
<ulside-navigationclass="navmetismenu"ng-include="'navigations'"id="side-menu"></ul><scriptid="navigations"type="text/ng-template"><ling-repeat="navsinfunctionGroups"><ahref="`navs`.`functionpoint`"><spanclass="nav-label">`navs`.`name`</span><spanng-if="navs.children.length"class="faarrow"></span></a><ulng-if="navs.children.length"ng-include="'navigations'"class="navnav-second-level"ng-init="functionGroups=navs.children"></ul></li></script>
另一种采用指令的方式:(未测试)
angular.module('demo').directive('recursion',function($compile){functioncpl(element,link){//Normalizethelinkparameterif(angular.isFunction(link)){link={post:link};}//Breaktherecursionloopbyremovingthecontentsvarcontents=element.contents().remove();varcompiledContents;return{pre:(link&&link.pre)?link.pre:null,/***Compilesandre-addsthecontents*/post:function(scope,element){//Compilethecontentsif(!compiledContents){compiledContents=$compile(contents);}//Re-addthecompiledcontentstotheelementcompiledContents(scope,function(clone){element.append(clone);});//Callthepost-linkingfunction,ifanyif(link&&link.post){link.post.apply(null,arguments);}}};}return{restrict:'A',scope:{recursion:'='},template:'<ling-repeat="iteminrecursion">\<ahref="`item`.`cateId`.html">`item`.`cateName`</a>\<ulrecursion="item.child">\</ul>\</li>',compile:function(element){returncpl(element,function(scope,iElement,iAttrs,controller,transcludeFn){//Defineyournormallinkfunctionhere.//Alternative:insteadofpassingafunction,//youcanalsopassanobjectwith//a'pre'-and'post'-linkfunction.});}};});
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。