I'm trying to use ng-options with a to bind a numeric integer value to a list of corresponding options:
angular.module('nonStringSelect', [])
.controller('MyCtrl', function($scope) {
$scope.loadedModels = [
{
id_category: 1,
title: 'Category A',
},
{
id_category: 2,
title: 'Category B',
},
{
id_category: 3,
title: 'Category C',
},
];
$scope.model = 3;
})
.directive('convertToNumber', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$parsers.push(function(val) {
return parseInt(val, 10);
});
ngModel.$formatters.push(function(val) {
return '' + val;
});
}
};
});
HTML:
<body ng-app="nonStringSelect" ng-controller="MyCtrl">
<select ng-model="model" ng-options="item.title for item in loadedModels track by item.id_category" convert-to-number>
</select>
{{ model }}
</body>
At first, I tried using
<select ng-model="model" ng-options="item.id_category as item.title for item in loadedModels" convert-to-number>
but it produced
<option value="number:1" label="Category A">Category A</option>
Now I use
ng-options="item.title for item in loadedModels track by item.id_category"
and it generated the correct options:
<option value="1" label="Category A">Category A</option>
I tried to follow the answer described here but it doesn't work. When the page is loaded no item is selected in the list and whenever I select any item the model becomes NaN.
Here is a plnkr.