ng-select gives only string, but I want an integer ng-select gives only string, but I want an integer angularjs angularjs

ng-select gives only string, but I want an integer


There is an easier way:

Just use value*1 as your id, that will convert the string to int without changing the value... assuming the id is an integer.

so the result is>

<div ng-app ng-controller="MyCtrl">    <select ng-model="selectedItem" ng-options="selectedItem*1 as selectedItem for selectedItem in values"></select>    selectedItem: {{selectedItem}}</div>

This will work in more cases, since indexOf is not available in objects, only in arrays. This solution works for objects with integers as keys (for example if some keys are missing, or if you use db ids)


Most solutions discussed here require using the ngOptions directive instead of using static <option> elements in the HTML code, as was the case in the OP's code.

Angular 1.6.x

Edit If you use Angular 1.6.x, just use the ng-value directive and it will work as expected.

angular.module('nonStringSelect', []).run(function($rootScope) {  $rootScope.model = { id: 2 };})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script><div ng-app="nonStringSelect">  <select ng-model="model.id">    <option ng-value="0">Zero</option>    <option ng-value="1">One</option>    <option ng-value="2">Two</option>  </select>    {{ model }}</div>