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

Problem

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 ={
         0:'Apple0',
         1:'Apple1',
         2:'Apple2',
         3:'Apple3'
};

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

Solution

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="apple.id as apple.name for apple in apples"
Solution courtesy of: JB Nizet

Discussion

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 = [
    'Apple0',
    'Apple1',
    'Apple2',
    'Apple3'
];

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.