lexeme
lexeme

Reputation: 2973

Value of the model includes unnecessary text

Why does the itemsPerPage model get assigned the value of 5 per page if I specify {{item}} per page inside the option tag?

<!-- the normal case: itemsPerPage is 5, 10, 20 -->
<select ng-model="itemsPerPage" ng-init="items = [5, 10, 20]">
    <option ng-repeat="item in items">{{item}}</option>
</select>

<!-- the odd case: itemsPerPage is 5 per page, 10 per page, 20 per page -->
<select ng-model="itemsPerPage" ng-init="items = [5, 10, 20]">
    <option ng-repeat="item in items">{{item}} per page</option>
</select>

Upvotes: 1

Views: 38

Answers (2)

lexeme
lexeme

Reputation: 2973

I've found the solution:

I use

<select ng-model="itemsPerPage" ng-options="'show ' + item + ' items' for item in [5, 10, 25]" class="left"></select>

with

$scope.itemsPerPage = 5; 

assigned in the corresponding controller;

Upvotes: 0

Vladimir Gordienko
Vladimir Gordienko

Reputation: 3470

Because you do not assign value attribute for option tags, in that case value will be all text inside open and close selected 'option' tag, use 'ng-options' directive for build select optons

https://docs.angularjs.org/api/ng/directive/select

Example:

<select>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

Select "Three" and select value will be "3" as this option has value attribute and it is "3"

<select>
    <option>One</option>
    <option>Two</option>
    <option>Three</option>
</select>

Select "Three" and select value will be "Three" as this option has no value and select will get as value text inside

You'r first and second examples are the same, without value attribute. difference only in text inside .

If you use ng-options angular directive it will build select correct

<select ng-model="selItem" ng-init="items = [{id: 1, name: 'One'},{id: 2, name: 'Two'},{id: 3, name: 'Three'}]" ng-options="item.id as item.name for item in items">
</select>

look this http://jsfiddle.net/em3f8t9r/2/

Upvotes: 1

Related Questions