将数组转换为嵌套列表

时间:2015-07-13 04:23:53

标签: javascript angularjs

对Angular很新,我试图做一些非传统的操作。

说我有这样一个数组:["A","B","C","D","E","F","G"];

我想输出这样的HTML:

<ul>
    <li>A</li>
    <ul>
        <li>B</li>
        <ul>
            <li>C</li>
            <ul>
                <li>D</li>
                <ul>
                    <li>E</li>
                    <ul>
                        <li>F</li>
                        <ul>
                            <li>G</li>
                        </ul>
                    </ul>
                </ul>
            </ul>
        </ul>
    </ul>
</ul>

基本上,我只想继续嵌套,直到我到达数组的末尾。我无法弄清楚如何做到这一点。遗憾的是,我没有任何代码示例,因为如果不在一个while循环内冻结浏览器,我将无法完成此操作。

然而,这就是我所拥有的:

<div class="trail" ng-include="'trail'"></div>
<script type="text/ng-template" id="trail">
    <li>{{trailItem.content}}<li>
    <ul ng-repeat="trailItem in post.trail" ng-include="'trail'">
    </ul>
</script>

以上内容适用于数据结构,其中post是一个对象数组,其中content是一个属性。

但是,这会永远循环,浏览器会冻结。

3 个答案:

答案 0 :(得分:0)

var ary = ["A", "B", "C", "D", "E", "F", "G"];
var $container = $('<div></div>');
var dom = $container;
for (var i = 0; i < ary.length; i++) {
    dom = appendDom(dom, ary[i]);
}
function appendDom(dom, value) {
    var $ul = $('<ul><li>' + value + '</li></ul>');
    $(dom).append($ul);
    return $ul;
}
alert($container.html());

输出是您的需要

答案 1 :(得分:0)

我无法让它与您发布的一维数组完全一致,但我确实在http://benfoster.io/blog/angularjs-recursive-templates

找到了一个jsfiddle的好例子

此外,这是我到目前为止:

http://jsfiddle.net/haydenk/s19v2f1m/3/

<div ng-controller="MainCtrl">
    <script type="text/ng-template" id="awesomeTree">
    {{ awesomeThing }}
    <ul ng-if="awesomeThings">
        <li ng-repeat="awesomeThing in awesomeThings" ng-include="'awesomeTree'"></li>
    </ul>
    </script>
    <ul>
        <li ng-repeat="awesomeThing in awesomeThings" ng-include="'awesomeTree'"></li>
    </ul>
</div>



var app = angular.module('testApp',['ngAnimate']);

app.controller('MainCtrl', function ($scope) {
    $scope.awesomeThings = ['A','B','C','D','E','F','G','H'];
  });

答案 2 :(得分:0)

尝试这个。

HTML:

<div  ng-controller="testCtrl">
    <div add-ul-li  arr-list-val=arrList> 
    </div>
</div>

JS:

app.controller("testCtrl",function($scope){

    $scope.arrList = ["A","B","C","D","E","F","G"];


})
.directive("addUlLi",function(){
    var finalHtml="";
    return { 
        scope : {arrListVal: '='},

        link: function(scope,ele,attr){
             scope.arrListVal.reverse();

            angular.forEach(scope.arrListVal,function(oneElement,key){
                console.log(key)
                if(key==0){
                     finalHtml = "<ul> <li>"+oneElement+"</li> </ul>"; 

                }else{

                    finalHtml =  "<ul> <li>"+oneElement+" "+finalHtml+"</li> </ul>";

                }

                if((key+1)==scope.arrListVal.length){
                    ele.append(finalHtml);
                }
            })
        }
    }
})

选中此plunker