Search code examples
google-app-maker

Checking a comma separated string for a value within an binding


I want to create a visibility binding on an image. This image should show when a comma separated string from a calculated model contains a certain value.

The values to be checked could be: "Apple, Pear, Banana". Now I wanna set the visibility of the image to true if the string contains "Pear".

What I can do is:

@datasource.item.Fruits === "Pear" ? true : false;

The problem is that this will only trigger if the value is exactly "Pear" but not if there are multiple values.

I could try to include every possible combination in the binding but that seems to be a little bit overkill.

Anyone an idea to solve this?

Thanks 🍪


Solution

  • First you will want to convert your comma separated string to an array by using the JavaScript split function, then you will want to use the JS indexOf function to look for your value inside this array. The result will be a binding that looks like this:

    (@datasource.item.Fruits).split(‘,’).indexOf(‘Pear’) > -1
    

    Make sure you include the () around the datasource item binding otherwise you can’t use the JS functions on it.