Markus Johansson
Markus Johansson

Reputation: 3773

Blank option added for selected option as language changes

I have the following code to show a multiselect with some options. All options are translated using a translation filter (angular-translate).

<select multiple class="form-control" ng-model="field.value">
    <option ng-repeat="option in field.options()">{{option.name | translate}}</option>
</select>

It will produce something like this:

['Orange', 'Apple', 'Banana']

If some options are selected and the language is changed, angularjs will not find a match for the selected items ('Orange' != 'Apelsin'), so it will add empty ones and I will end up with:

[' ', ' ', 'Apelsin', 'Äpple', 'Banan']

How can I avoid that the change of language messes up my select list? I would want to put an ID on each option, so that it will try to match that instead of the translated name.

Upvotes: 0

Views: 126

Answers (1)

Keep translated name inside tag, but also use un-translated name as value attribute of option.

<option ng-repeat="option in options">{{option | translate }}

to

<option value="{{option}}" ng-repeat="option in options">{{option | translate }}

It's not Angular specific http://www.w3schools.com/tags/att_option_value.asp

I had same issue and this solved it to me...


Plus, set some option as default in controller

Template

ng-model="field.value"

Controller

$scope.field.value = options[0] // First will be selected by default

Upvotes: 1

Related Questions