Bob Horn
Bob Horn

Reputation: 34297

ng-if and $index off by 1

I'm trying to display a schedule and I want to create a break after each group of matches within a week. For example, I want an <hr> after the first five matches in week 1. Then again after five matches of week 2. What I have now includes the first six matches, and then every five after that. Why? What do I need to do to break after every five?

Note: As an additional enhancement, it would be nice to break when the week changes, and not just assume there will be five matches each week. If someone has a way to solve that as well, that would be great.

As you can see below, the first six matches show, which incorrectly includes the first match of week two.

enter image description here

This is in my HTML:

<div ng-repeat="match in state.eastSchedule.Matches">
        <div class="row">
            <div class="col-xs-1 text-center">{{match.WeekNumber}}</div>
            <div class="col-xs-2">{{match.AwayPlayer}}</div>
            <div class="col-xs-2">{{match.HomePlayer}}</div>
            <div class="col-xs-2">{{match.Score}}</div>
        </div>
        <hr ng-if="$index > 0 && $index % 5 == 0" style="border-color:black;" />
    </div>

I also tried removing the part about only using an index > 0, but then I get a break after the very first match, and then every five after that.

<hr ng-if="$index > 0 && $index % 5 == 0" style="border-color:black;" />

Upvotes: 0

Views: 2530

Answers (3)

Sunil D.
Sunil D.

Reputation: 18193

The HTML is structured so that the <div class="row"> appears before the <hr> tag.

So on the 6th iteration of the loop (second week, when $index is 5), it prints the <div class="row"> for the first item in the second week then the <hr>.

To fix you can move the <hr> tag so that it is above <div class="row">.

Upvotes: 2

Akash Bhandwalkar
Akash Bhandwalkar

Reputation: 901

$index start with 0. so in first case you are printing 6 values i.e. index 0 1 2 3 4 5. after that it will work fine like it will take next 5.

Upvotes: 0

rejo
rejo

Reputation: 3350

Try this,

var app = angular.module('plunker', []);

app.controller('MainController', function($scope) {
  $scope.arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
});
<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link href="style.css" rel="stylesheet" />
    <script data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js" data-require="[email protected]"></script>
    <script src="app.js"></script>
  </head>

  <body ng-app="plunker" >
    <div ng-controller="MainController">
    
    <div ng-repeat="item in arr">
      {{item}}
      <hr ng-if="(($index+1) % 5) == 0">
    </div>
     
     
    </div>
    
  </body>

</html>

Upvotes: 0

Related Questions