Reputation: 509
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
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
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
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