递归ng-重复x次 [英] Recursive ng-repeat x times

查看:95
本文介绍了递归ng-重复x次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的角度模板中重复一个深层嵌套的javascript对象。问题是我无法控制数据的传递方式,也无法知道数据的嵌套程度。

I need to repeat over a deeply nested javascript object in my angular template. The problem is that I have no control over how the data is handed to me, and no way of knowing how deeply nested the data will be.

数据看起来像这样

{
    category_name: 'cat1'
    children: [
        {
            category_name: 'cat1a',
            children: [...]            
        }
    ]
}

模板

<div ng-repeat="cat in categories">
    <div ng-repeat="subcat in cat.children">
        {{subcat.name}}
        <!-- 
            would like to programatically place an ng-repeat here too 
            if subcat.children.length > 0 
        -->
    </div>
    {{cat.name}}
</div>

这会检查两个级别,但是如何在没有孩子的情况下递归重复?我想我需要创建一个自定义指令,根据需要编译一个新的ng-repeat,我只是不确定如何去做。

This checks two levels deep, but how can I recursively repeat until there are no children left? I'm thinking I need to create a custom directive that compiles a new ng-repeat as required, I'm just not sure how to go about it.

推荐答案

您可以使用 ng-include 指令脚本类型 ng-template / text 并递归调用它来编写 n 子项。 ( PLUNKER

You can use ng-include with a directive script type ng-template/text and call it recursively to write n children. (PLUNKER)

<body ng-controller="MainCtrl as vm">
  <script type="text/ng-template" id="nested.html">
    {{item.category_name}}
    <ul>
      <li ng-repeat="item in item.children" ng-include="'nested.html'"></li>
    </ul>
  </script>

  <ul>
    <li ng-repeat="item in vm.data" ng-include="'nested.html'"></li>
  </ul>
</body>




  • 检查角度文档以获取更多信息 https://docs.angularjs.org/api/ng/directive/script

    • Check angular docs for more info: https://docs.angularjs.org/api/ng/directive/script
    • 这篇关于递归ng-重复x次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆