简体   繁体   中英

AngularJS only show first date div in loop (with updating array object)

I am trying to render a javascript object to a template in Angular ~1.2.24

Only the first occurence of item.day should be shown.

example object:

$scope.listtrail = [{
    day: '2015-08-15',
    id: 123,
    timestamp: '2015-08-15 12:23:12'
},{
    day: '2015-08-15',
    id: 122,
    timestamp: '2015-08-15 12:43:34'
},{
    day: '2015-08-15',
    id: 121,
    timestamp: '2015-08-15 14:12:56'
},{
    day: '2015-08-14',
    id: 120,
    timestamp: '2015-08-14 11:12:09'
},{
    day: '2015-08-14',
    id: 118,
    timestamp: '2015-08-14 10:11:02'
}]

example template section:

<div ng-repeat="item in listtrail">
    <div>{{item.day}}</div>
    <div>{{item.timestamp}}</div>
</div>

example template output goal:

<div>
    <div>2015-08-15</div>
    <div>2015-08-15 12:23:12</div>
</div>
<div>
    <div>2015-08-15 12:43:34</div>
</div>
<div>
    <div>2015-08-15 14:12:56</div>
</div>
<div>
    <div>2015-08-14</div>
    <div>2015-08-14 11:12:09</div>
</div>
<div>
    <div>2015-08-14 10:11:02</div>
</div>

Please note that the javascript array also gets prepended (as it grows) every few seconds using an internal splice function (just to bear in mind).

Nice solution would be to use angular-filter module. It could be then coded as:

<div ng-app="app">
  <div ng-controller="TestCtrl">
    <div ng-repeat="(key, value) in listtrail | groupBy: 'day'">
        <div>{{ key }}</div>
        <div ng-repeat="item in value">{{item.timestamp}}</div>
    </div>
  </div>
</div>

Just take a look at JSFiddle

<div ng-repeat="item in listtrail">
  <div ng-if="listtrail[$index-1].day != item.day">{{item.day}}</div>
  <div>{{item.timestamp}}</div>
 </div>

This should work just fine: https://jsfiddle.net/2o5nwy2r/5/

However using a $filter to do some sort of groupBy on the ng-repeat might be more resilient. Take a look at angular-filter https://github.com/a8m/angular-filter

You need to match with previous day value

<div ng-repeat="item in listtrail">
  <div ng-if='listtrail[$index -1].day != item.day'>{{item.day}}</div>
  <div>{{item.timestamp}}</div>
</div>

You need to keep your records in order of day :)

See this jsFiddle

I had the same answer as the other two, but with the additional check for $index == 0 :

<div ng-app>
  <div ng-controller="TestCtrl">
    <div ng-repeat="item in listtrail">
      <div ng-if="$index == 0 || listtrail[$index-1].day != item.day" ng->{{item.day}}</div>
      <div>{{item.timestamp}}</div>
    </div>
  </div>
</div>

Not checking doesn't appear to cause an error, but it offends my sensibilities.

https://jsfiddle.net/2o5nwy2r/6/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM