Angular JS如何使用ng-repeat获取模型中相同键的所有值

时间:2014-08-02 22:49:14

标签: json angularjs ng-repeat

以下是Angular中使用的JSON模型。

$scope.numbers = [
{"0":"206-000-0008","connection":"206-000-0008","1":"dandelion","topic":"dandelion"},
{"0":"206-000-0008","connection":"206-000-0008","1":"burdock","topic":"burdock"},
{"0":"206-000-0008","connection":"206-000-0008","1":"cinnamon","topic":"cinnamon"},  
{"0":"206-000-0003","connection":"206-000-0003","1":"jasmine","topic":"jasmine"},
{"0":"206-000-0003","connection":"206-000-0003","1":"mint","topic":"mint"},
{"0":"206-000-0003","connection":"206-000-0003","1":"earlgray","topic":"earlgray"}
]

我想循环显示所有具有共同“连接”的主题的模型。 使用样本模型,显示应为:

206-000-0008
dandelion, burdock, cinnamon

206-000-0003
jasmine, mint, earlgray

我尝试过以下无法正确显示的内容:

<ul><!-- outer loop begin -->
    <li ng-repeat="whatever in numbers track by $index">

        {{whatever.connection}}

        <ul data-ng-show="whatever"><!-- inner loop begin -->
            <li ng-repeat="topic in whatever.connection track by $index">

                {{whatever.topic}}                   

            </li>
        </ul><!-- inner loop end -->

    </li>
</ul><!-- outer loop end -->

1 个答案:

答案 0 :(得分:1)

一种选择是调用ng-repeat中的函数,以适当的格式生成数据。

通过迭代$ scope.numbers数组,您可以生成一个新对象(名为result),其中每个键都是connection,每个值都是逗号分隔的{{1}列表}}。如果$ scope.numbers很小(例如&lt; 1000元素),那么您不必担心性能。

我还没有测试过,但下面的代码应该可以使用。

在您的控制器中:

topics

在您看来:

$scope.groupByNumbers = function() {
    var result = {};
    var numbers = $scope.numbers;

    for (var i = 0; i < numbers.length; i++) {
        var num = numbers[i];
        var value = result[num.connection];
        var topic = num.topic;
        result[num.connection] = (value) ? value + ', ' + topic : topic;
    }

    return result;
}