當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
AngularJS recursive(递归)
生活随笔
收集整理的這篇文章主要介紹了
AngularJS recursive(递归)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
工作中我們經常要遍歷多層數據,如果數據是已知層級的話,用 ng-repeat 就搞定了,要是數據深度是無限的呢,或者我們要實現一個無限層級的 tree 的時候,該怎么辦?
答案是使用 ng-include 指令遞歸模板。假如我們有如下數據:
$scope.categories = [{ title: 'Computers',categories: [{title: 'Laptops',categories: [{title: 'Ultrabooks'},{title: 'Macbooks' }]},{title: 'Desktops'},{title: 'Tablets',categories: [{ title: 'Apple'},{title: 'Android'}] }]},{title: 'Printers'} ];//注意這組數據會動態增加并無限延伸下去
我們的目標是呈現出一個 tree ,這時我們就要用到一個模板來遞歸渲染 tree 中的每一級,首先要定義一個內聯模板:
<script type="text/ng-template" id="categoryTree">{{ category.title }}<ul ng-if="category.categories"><li ng-repeat="category in category.categories" ng-include="'categoryTree'"> </li></ul> </script>然后在根節點引用遞歸模板:
<ul><li ng-repeat="category in categories" ng-include="'categoryTree'"></li> </ul>實現原理:
ng-repeat 在每次迭代數據的時候會創建一個子 scope 。我們在模板中引用的 category 變量是屬于當前的那次迭代,遞歸模板能正常工作的原因是我們在模板內部和外部都使用了相同的變量 category 。如果你想使用不同的變量名,那么你應該先使用 ng-init 初始化:
<li ng-repeat="parentCategory in categories" ng-include="'categoryTree'" ng-init="category=parentCategory"> </li>?
參考:http://benfoster.io/blog/angularjs-recursive-templates
轉載于:https://www.cnblogs.com/kuangliu/p/4146705.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的AngularJS recursive(递归)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android窗口管理服务WindowM
- 下一篇: gradle idea java ssm