工作中我们经常要遍历多层数据,如果数据是已知层级的话,用 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

posted on 2014-12-05 15:04  狂流  阅读(1739)  评论(0编辑  收藏  举报