Change color depending on it is odd or even

Can a list of each change some value as the background color depending on whether it is odd or even?

Like (but the number of element depend of a Database): file

Thanks!

At the moment, we don’t support this kind of thing out-of-the-box. One way to do it might be to decorate your original data before it gets to the view in markup. For example:

var items = []; // Some array of items
for (var i = 0; i < items.length; i++) {
    items[i].colorScheme = (i % 1) == 0 ? "dark" : "light";
}

Then this colorScheme field could be used with something like Match/Case in UX to get the appropriate look:

<Match Value="{colorScheme}">
    <Case String="dark">
        <!-- Show dark item -->
    </Case>
    <Case String="light">
        <!-- Show light item -->
    </Case>
</Match>

I understand that the for-loop approach is a bit sub-par though; I’ve made a ticket internally that proposes to add a mapi function to Observable that would work similarly to map, but the mapping function would as input also take the index of the item being mapped. With that, you could do it like this:

var items = new Observable(...); // Same as items before, but this time it's an Observable
var groupItems = items.mapi(function(index, item) {
    // Ideally you would actually clone item here, but I didn't in this example for simplicity
    var newItem = item;
    newItem.colorScheme = (index % 1) == 0 ? "dark" : "light";
    return newItem;
});

This mapi will probably go in, and I can let you know when it does; it may not though. Either way we should have an elegant way to handle these kinds of cases.

Great! Thanks for the example. This could work fine to my purpose.

Will be very usseful to have a mapi function!

After discussing it more internally we’re going with just extending the existing map function to also be able to take a function that expects both the item and the index. I’ve made a ticket internally for adding this. I’ll let you know when it’s ready :slight_smile:

It looks like this new form of map is going to be in the next release :slight_smile: