The goal is to create this
<h3>11.4.2013</h3>
<ul>
<li>entry 1</li>
<li>entry 2</li>
<li>entry 3</li>
</ul>
<h3>10.4.2013</h3>
<ul>
<li>entry 4</li>
<li>entry 5</li>
<li>entry 6</li>
</ul>
from this
[
{
"name": "entry1",
"date": "11.4.2013"
},
{
"name": "entry2",
"date": "11.4.2013"
},
{
"name": "entry3",
"date": "11.4.2013"
},
{
"name": "entry4",
"date": "10.4.2013"
},
{
"name": "entry5",
"date": "10.4.2013"
},
{
"name": "entry6",
"date": "10.4.2013"
}
]
The problem is that ng-repeat would have to be on li
so I wouldn't never be able to do this using ng-repeat, is that right? I found this http://jsfiddle.net/mrajcok/CvKNc/ example from Mark Rajnoc, but it's still pretty limiting..
What other choices do I have? Write my own ng-repeat like directive? Or is there another way to do it without writting one?
You could write your own filter that filters out the unique dates for an outer ng-repeat, something like:
filter('unique',function(){
return function(items,field){
var ret = [], found={};
for(var i in items){
var item = items[i][field];
if(!found[item]){
found[item]=true;
ret.push(items[i]);
}
}
return ret;
}
});
with the following markup:
<div ng-repeat="dateItem in items | unique:'date' | orderBy:'date'">
<h3>{{dateItem.date}}</h3>
<ul>
<li ng-repeat="item in items | filter:dateItem.date">
{{item.name}}
</li>
</ul>
</div>
Have a look at this working plnkr example -- or this updated example with adding items
However, if your going to have a lot of items (hundreds or thousands) this solution is not the most optimal. An alternative approach would be to create a more optimal data structure. You can even get this to work with your original data structure by adding a $watch - something like:
$scope.$watch('items',function(){
var itemDateMap = {};
for(var i=0; i<$scope.items.length; i++){
var item = $scope.items[i], key = item.date;
if(!itemDateMap[key]){
itemDateMap[key] = [];
}
itemDateMap[key].push(item);
}
$scope.itemDateMap=itemDateMap;
},true);
Works with this markup:
<div ng-repeat="(date,subItems) in itemDateMap">
<h3>{{date}}</h3>
<ul>
<li ng-repeat="item in subItems">
{{item.name}}
</li>
</ul>
</div>
Here is an example where you can add lots of random items.
When I have same needs like yours, I used Object instead of Array.
<div ng-repeat="item in data">
<h1>{{item.date}}</h1>
<ul ng-repeat="name in item.names">
<li>{{name}}</li>
</ul>
</div>
http://jsfiddle.net/shoma/DqDsE/1/
This question page would help you.
What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.