Push Array in alternate colors

Hi. How can I push an array and display its color in an alternate way?

This will be the output:

This COLOR is RED
This COLOR is GREEN
This COLOR is RED
This COLOR is GREEN

you could use the modulo operator --> it determines the “rest” of a division like 2 / 2 = 1 rest 0, but 3 / 2 = 1 rest 1.

Extended Version:
With you know that you have only two colors you can check the $index key in your ng-repeat in combination with your two colors: $index === 1 || ($index > 1 && $index % 2 === 1) --> use color2 in other cases the $index is 0 or 1 (the first list entry or second or it is an even number like 2, 4, 6) and you can use color1

<div ng-repeat="item in items" ng-class="{color1: $index === 1 || ($index > 1 && $index % 2 === 1), color2: !$index || $index % 2 === 0}">
 alternated color
</div>

Look here: http://play.ionic.io/app/645cea559a10

Simple version
You can use this simply with more colors:

  1. check if $index < color number --> so you can simply use colors[$index]
  2. check if $index >= color.number --> so you can use colors[$index % colors.length]
    Look here http://play.ionic.io/app/f8451ebc8004
1 Like

You could also use ng-class-odd and ng-class-even if it’s just the display you are talking about, e.g.

<ion-list >
  <ion-item ng-repeat="name in names" ng-class-odd="'balanced'" ng-class-even="'positive'">
    {{name}}
  </ion-item>
</ion-list>

http://play.ionic.io/app/a6c56c864c7d

2 Likes

Wow , Thanks Guys, I got one more question ,How About if i want to determine the color of the array , just like this

If correct it will turn into green
else it will turn into red ?

CORRECT //This color wil turn into GREEN
WRONG //This color wil turn into RED
WRONG //This color wil turn into RED
WRONG //This color wil turn into RED
CORRECT //This color wil turn into GREEN
CORRECT //This color wil turn into GREEN

use ngClass

<div ng-repeat="item in items" ng-class="{red: !item.correct, green: item.correct}">...</div>

I’ve try your code , Why isn’t working ? I inserted this to my style.css ,

.red {
color: red;
}

.green{
color: green;
}

it depends how an item looks like in my example i am assuming that an array entry looks like this:

{
  correct: true,
  ......
}

I’m confused with this code , can you please put the full code ? Thanks :slight_smile: I tried it many time and its not working :frowning: ,

http://play.ionic.io/app/6a15c9702258

That is nice. But do you know how to change the background color , not the text color.