手风琴模式的菜单:
在项目中我们会遇到不知层级的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){ //Normalizethelinkparameter if(angular.isFunction(link)){ link={post:link}; } //Breaktherecursionloopbyremovingthecontents varcontents=element.contents().remove(); varcompiledContents; return{ pre:(link&&link.pre)?link.pre:null,/** *Compilesandre-addsthecontents */ post:function(scope,element){ //Compilethecontents if(!compiledContents){ compiledContents=$compile(contents); } //Re-addthecompiledcontentstotheelement compiledContents(scope,function(clone){ element.append(clone); }); //Callthepost-linkingfunction,ifany if(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. }); } }; });