AngularJS: Select with ng-options- how to pass value as integer?


I am having an issue with my select form. When I select any option, the value that is being passed is of a string type, instead of number type. Here is my object that I use for ng-repeat:

$scope.apples ={

And here is my select, which passes string, instead of number:

 <select ng-model="test" ng-options="key as value for (key,value) in apples"></select>

Any ideas?

Problem courtesy of: uksz


Every time you're iterating on object fields, IMO, there is a design problem. Use an array:

$scope.apples = [
    id: 0,
    name: 'Apple0'
    id: 1,
    name: 'Apple1'

and in the view:

ng-options=" as for apple in apples"
Solution courtesy of: JB Nizet


Very simple approach is to actually cast string to number (note, + operator):

ng-options="+key as value for (key,value) in apples"

It's also possible to use array as data structure:

$scope.apples = [

and then

ng-options="apples.indexOf(apple) as apple for apple in apples"
Discussion courtesy of: dfsq

This recipe can be found in it's original form on Stack Over Flow.