简体   繁体   中英

Conditionally add attribute in select option with Aurelia

I am simply trying to create a repeat.for loop which will generate the options for a select element in a form in my application. I wish to add the selected attribute to the last option of my select element but cannot figure out how to manage it. The code for my select looks as follows:

<select select class="browser-default" value.bind="maxPlayers">
  <option repeat.for="num of numPlayers" value.bind="num">${num}</option>
</select>

and the numPlayers property of my view-model class is just a simple array:

numPlayers = [2, 3, 4];

So my question is how can I add the selected attribute to only the last option element in my select element? I know that there is a boolean value named $last that indicates whether or not I am on the last element, but I cannot figure out how to properly incorporate that. It seems that I should be able to get it work by adding selected.bind="$last" to the option element, but that does not seem to have any effect.

Use model.bind on the option elements. The HTMLOptionElement's value property coerces all values to strings.

Here's an example: https://gist.run?id=9bdbf2518dbd1169d8607f712b09d41b

app.html

<template>
  <select select class="browser-default" value.bind="maxPlayers">
    <option repeat.for="num of numPlayers" model.bind="num">${num}</option>
  </select>
</template>

app.js

export class App {
  numPlayers = [2, 3, 4];
  maxPlayers = 4;
}

More info on binding select elements here: http://aurelia.io/docs.html#/aurelia/framework/1.0.0-beta.1.1.4/doc/article/cheat-sheet/5

What you need is to compare the $last variable with the current $index inside the loop like this.

<select select class="browser-default" value.bind="maxPlayers">
  <option repeat.for="num of numPlayers" value.bind="num" selected.bind="$index === $last">${num}</option>
</select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM