来自Drupal服务器响应的表单数组<ion-list>

时间:2015-11-09 07:40:52

标签: angularjs ionic

我想要的是Ionic http://codepen.io/anon/pen/epPPbm中的手风琴列表。问题出在我在Drupal上从服务器收到的数据中。让我们说我的html文件是这样的

    <ion-list ng-repeat="category in categories">
        <ion-item class="item item-stable item-icon-left">
            {{category.name}}
        </ion-item>
        <ion-list ng-repeat="subcategory in category.subcategories">
            <ion-item class="item item-positive item-icon-left">
                {{subcategory.name}}
            </ion-item>
        </ion-list>
    </ion-list>

从服务器我得到这个

[{"tid":"17","depth":0,"parents":["0"]},{"tid":"12","depth":1,"parents":["15","17"]},{"tid":"1","depth":0,"parents":["0"]},{"tid":"15","depth":0,"parents":["0"]},{"tid":"16","depth":1,"parents":["15"]},{"tid":"13","depth":1,"parents":["15"]},{"tid":"12","depth":1,"parents":["15","17"]},{"tid":"11","depth":0,"parents":["0"]},{"tid":"14","depth":0,"parents":["0"]}]

此处深度01相应地表示类别和子类别。 Parents是子类别的父tid数组。我需要来自我的html视图的响应的表单数组。现在我这样做,这很复杂

    for (var i = 0; i < categories.length; ++i) {
        if (categories[i].depth == 0)
            $scope.categories.push(categories[i]);
    }
    for (var i = 0; i < $scope.categories.length; ++i)
        $scope.categories[i].subcategories = [];
    for (var i = 0; i < categories.length; ++i) {
        if (categories[i].depth == 1) {
            for (var j = 0; j < categories[i].parents.length; ++j) {
                for (var k = 0; k < categories.length; ++k) {
                    if (categories[k].tid === categories[i].parents[j]) {
                        $scope.categories[k].subcategories.push(categories[i]);
                    }
                }
            }
        }
    }

可能有更简单的方法来做到这一点。

1 个答案:

答案 0 :(得分:1)

当您需要创建嵌套类别和子类别列表时,您将无法避免某种嵌套循环,但我相信您可以通过创建哈希来使代码更具可读性(并且更快)查找以构建数组。例如:

// build a lookup and add the primary categories to the scope
var tidLookup = {};
angular.forEach(categories, function(cat){
    if(cat.depth === 0){
        cat.subcategories = [];
        $scope.categories.push(cat);
    }
    tidLookup[cat.tid] = cat;
});

// go through each subcategory and add it to the appropriate parent
angular.forEach(categories, function(cat){
    angular.forEach(cat.parents, function(parent){
        if(tidLookup[parent]){
            tidLookup[parent].subcategories.push(cat);
        }
    });
});

我已在此处更新了您的codepen:http://codepen.io/anon/pen/epPQpZ

另请注意,您的codepen结果中的重复项是因为您复制了示例数据数组。

更新

如果您需要处理来自服务器的重复子类别,我会尝试删除get上的重复项,或者只保留所有已处理子类别的第二个哈希查找,这可以在处理时进行检查。