简体   繁体   中英

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).

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.

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.

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);

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