Angular 1.5 - Insert custom element after last element with certain property

Viewed 47

Let's assume I'm having following code:

<li ng-repeat="task in todoList">
    {{task.name}}
</li>

And let's assume this is my dataset ( Assuming it's ordered by when, from now to future ) :

var todoList = [ { name : 'Work hard', when : 'Today'}, { name : 'Play hard', when : 'Today'}, { name : 'Relax hard', when : 'This week'}, ]

How can I detect in the ng-repeat when the current repeated item is the last item with the property when set to Today ?

So I'll end up something with something like this

<li ng-repeat="task in todoList">
    {{task.name}}
</li>
<!-- If last of current period, then show this -->
<li>
    <h3>Next period</h3>
</li>
3 Answers

You can try grouping the data by when, and repeating on the result set:

<ul ng-repeat="(when, tasks) in todoList | groupBy: 'when'">
  When: {{ when }}
  <li ng-repeat="task in tasks track by $index">
    <span ng-hide="$last">{{task.name}}</span>
    <h3 ng-show="$last">Next period</h3>
  </li>
</ul>

Edit 1:

If you just want to show the data of Today, you can just filter out the todoList, and then render it:

<li ng-repeat="task in todoList | filter:{ when: 'Today' }">
  <span ng-hide="$last">{{task.name}}</span>
  <h3 ng-show="$last">Next period</h3>
</li>

You have to create a method that checks if the current item is the last today:

<li ng-repeat="task in todoList">
    <div ng-switch="lastToday(task)">
        <div ng-switch-when="false">{{task.name}}</div>
        <h3 ng-switch-when="true">Next period</h3>
    </div>
</li>

$scope.lastToday = function(task) {
    return ($scope.todoList.reverse().find(t => t.when === 'Today') || {} ).name === task.name;
}
<li ng-repeat="task in todoList" ng-show="!$last">
    {{task.name}}
</li>
  <li ng-repeat="task in todoList" ng-show="$last">
   <h3>Next period</h3>
</li>

$last will help on this

Related