zoukankan      html  css  js  c++  java
  • 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


    作者:狂流
    出处:http://www.cnblogs.com/kuangliu/
    欢迎转载,分享快乐! 如果觉得这篇文章对你有用,请抖抖小手,推荐一下!

  • 相关阅读:
    微信分享相关
    移动端界面适配
    MongoDB安装使用
    MongoDB可视化工具RoboMongo
    PhotoSwipe图片展示插件
    BootStrap下拉框搜索功能
    Node.js 特点
    原生node实现本地静态页面的展示
    阿里巴巴电话初面
    react动态添加多个输入框
  • 原文地址:https://www.cnblogs.com/kuangliu/p/4146705.html
Copyright © 2011-2022 走看看