Я хочу отобразить список записей. Данные представляют собой список объектов, каждый из которых выглядит следующим образом:
{
date: "01/01/2001",
time: "04:28 AM",
message: "message strings here."
}
Я хочу отобразить их так, как они группируются по дате. Как это:
08/01/2005
04:28 AM message strings here.
04:20 AM message strings here.
02:12 AM message strings here.
07/05/2005
03:32 PM message strings here.
02:12 PM message strings here.
Это мой код:
<div>{{date}}</div> <!--date is initialized in my angular controller to be the first date in the records.-->
<div ng-repeat="record in records">
<div ng-if="record.date != date" ng-model="date">{{record.date}}</div> <!--here I expect date would be updated to record.date.-->
<div>{{record.time}} {{record.message}}</div>
</div>
Но я получаю такой результат:
08/01/2005
04:28 AM message strings here.
04:20 AM message strings here.
02:12 AM message strings here.
07/05/2005
03:32 PM message strings here.
07/05/2005 //This is displayed, means the date is not updated when it reach the first 07/05/2005 above.
02:12 PM message strings here.
Я искал в Интернете, много привязки данных модели привязывает модель с помощью <input>
. Но я не хочу использовать тег ввода. И ng-модель в <div>
кажется, не обновляет модель до текста, отображаемого в <div>
. Интересно, какой правильный способ достичь этого.
Я устанавливаю пример, основанный на ваших данных о том, как это сделать: https://jsfiddle.net/63o96cf2/
Оригинальный ответ: qaru.site/questions/49388/...
Посмотреть:
<div ng-app ng-controller="Main">
<ul ng-repeat="group in recordsToFilter() | filter:filterRecords">
<b>{{group.date}}</b>
<li ng-repeat="record in records | filter:{date: group.date}">{{record.time}}: {{record.message}}</li>
</ul>
</div>
контроллер:
function Main($scope) {
$scope.records = [{
date: "01/01/2001",
time: "03:28 AM",
message: "message strings here."
}, {
date: "01/01/2001",
time: "04:28 AM",
message: "message strings here."
}, {
date: "01/01/2001",
time: "06:28 AM",
message: "message strings here."
}, {
date: "01/01/2002",
time: "04:28 AM",
message: "message strings here."
}, {
date: "01/01/2002",
time: "05:28 AM",
message: "message strings here."
}];
var indexedRecords = [];
$scope.recordsToFilter = function() {
indexedRecords = [];
return $scope.records;
}
$scope.filterRecords = function(record) {
var recordIsNew = indexedRecords.indexOf(record.date) == -1;
if (recordIsNew) {
indexedRecords.push(record.date);
}
return recordIsNew;
}
}
Вам необходимо использовать фильтр "groupBy" в https://github.com/a8m/angular-filter#groupby
HTML
<ul ng-repeat="record in records | groupBy:'date'">
{{ record.date }}
<li ng-repeat="player in value">
{{ record.time }} ...
</li>
</ul>