Search code examples
javascripthtmlangularjsng-options

Ng-options selecting value as a int instead of a string


I have an array of objects

usage: [{label: 'Main', value: '30' },{ label: 'Second', value: '27' },{ label: 'Third', value: '50' }];

This is how I use the ng-options

<select class="Input" ng-model="myCtrl.data.usages" ng-options="usage.value as usage.label  for usage in myCtrl.data.usages">

It seems to work as it selects the right value.. However it selects as a string. Is there a way to make it select / parse as integer? So instead of '27', it will save as 27


Solution

  • You could make a filter for this. This will allow you to parse and manipulate the value however you wish. Observe the following example...

    app.filter('num', function() {
        return function(input) {
            return parseInt(input, 10);
        };
    });
    

    <select 
        ng-options="(usage.value | num) as usage.label  for usage in myCtrl.data.usages">
    </select>
    

    JSFiddle Link - demo