ehannes
ehannes

Reputation: 509

AngularJS select integer value with HTML select tag

I'm new to AngularJS. I have a very simple task: select an integer value with angular using an HTML <select> tag.

<select ng-model="foo.bar">
    <option ng-repeat="option in options" value="{{option}}">{{option}}</option>
</select>

foo.bar holds an integer value. When I run the above code, the first generated option is: <option value="? number:32 ?"></option>. I have found out that the selected value is interpreted as a String. I want an Integer.

I have found some possible solutions, but they are either complex (like the documentation example to implement a convert-to-number-function) , or their options array looks different (mine is just a simple array of integers).

Upvotes: 3

Views: 2858

Answers (3)

Frederik Kammer
Frederik Kammer

Reputation: 3177

Instead of the option tag combined with ng-repeat you should use angulars ng-options directive like this:

<select ng-model="foo.bar" ng-options="option for option in options"></select>

If options is an array of integers, ng-model should contain an integer as well.

Upvotes: 5

Amit Sirohiya
Amit Sirohiya

Reputation: 333

Select dropdown will give you string value always, if you want it to be an integer covert it in controller

Controller -

var numValue = Number(foo.bar);

Upvotes: 0

Hoijof
Hoijof

Reputation: 1413

Select will give you a string. You will have to convert that string into a number in your controller code.

foo.bar = parseInt(foo.bar);

You may need to use a watch to look for changes in your foo.bar variable and then parse them to integer.

Take a look at https://docs.angularjs.org/api/ng/type/$rootScope.Scope and search for $watch.

Upvotes: 0

Related Questions