Erythros
Erythros

Reputation: 127

Searching for element in array in aurelia view

I am using if.bind to conditionally display elements in a view. In my current case, I have something similar to

<template>  
  <h2 if.bind="car.model === 'Ferrari' || car.model === 'Ford` || car.model === 'Renault'">
     ${ car.price}
  </h2>
</template>  

I am looking to shorten the if.bind to something like if.bind="car.model in allModels in order to avoid having many ||

(In PHP there's something like in_array)

What solutions do I have?

Upvotes: 1

Views: 1013

Answers (2)

Sean Hunter
Sean Hunter

Reputation: 1051

Adiga's response shows a convenient way to do this if you prefer not to make any changes to your view-model. One alternative you could consider is using a computed property and moving this logic into the view-model instead. You could do this leveraging using the computedFrom decorator:

app.js

import {computedFrom} from 'aurelia-framework'; 

export class App{
  car = { model : ''};

  constructor(){
    this.allModels = ['Ferrari','Ford','Renault'];
  }

  @computedFrom('car.model')
  get showCar() {
    return this.allModels.indexOf(this.car.model) > -1;
  }
}

Then in your view you could do something like this:

app.html

<template>
    <h2 if.bind="showCar">
        ${car.price}
    </h2>
</template>

That way you can clean up the view logic but also avoid dirty checking that would result from needing to watch and re-calculate the showCar property. Functionally the approaches are the same, though this approach may make life easier if you plan to unit test the view-model.

Upvotes: 3

adiga
adiga

Reputation: 35222

You can use javascript expressions inside if and show bindings in Aurelia. So, if you have a property called allModels: string[] in your class, you can simply use indexOf:

<h2 if.bind="allModels.indexOf(car.model) > -1">
    ${car.price}
</h2>

If you don't have allModels property, you could also hardcode:

if.bind="['Ferrari','Ford','Renault'].indexOf(car.model) > -1"

Upvotes: 2

Related Questions