Reputation: 11
The following is a JSON model used in Angular.
$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"}
]
I want to loop through the model displaying all topics that have a common "connection". Using the sample model, the display should be:
206-000-0008
dandelion, burdock, cinnamon
206-000-0003
jasmine, mint, earlgray
I've tried the following which does not display correctly:
<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 -->
Upvotes: 1
Views: 936
Reputation: 475
One option is to call a function in ng-repeat that generates the data in a proper format.
By iterating over the $scope.numbers array, you can generate a new object (called result
) where each key is the connection
and each value is the comma-separated list of topics
. If $scope.numbers is small (e.g. < 1000 elements), you won't have to worry about performance.
I haven't tested it, but the code below should work.
In your controller:
$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;
}
In your view:
<p ng-repeat="(key, value) in groupByNumbers()">
{{key}}<br />{{value}}
</p>
Upvotes: 1