I\'m trying to use ng-options with a to bind a numeric integer value to a list of corresponding options. In my controller, I have something like
Maybe it's a bit messy, but result can be achieved without special functions right in ng-options
<select ng-model="ctrl.selectedUnitOrdinal" ng-options="+(unit.id) as unit.text for unit in ctrl.unitsOptions"></select>
Very similarly to tymeJV's answer, simple workaround is to convert the default selection number to a string like this:
self.selectedUnitOrdinal = valueThatCameFromServer.toString();
This way, you don't have to hardcode the number, you can just convert any received value. It's an easy fix without any filters or directives.
You can also define filter number
, this filter will automatically parse string value to int:
<select ng-model="ctrl.selectedUnitOrdinal" ng-options="unit.id|number as unit.text for unit in ctrl.unitsOptions"></select>
angular.module('filters').filter('number', [function() {
return function(input) {
return parseInt(input, 10);
};
}]);
Angular is seeing your id
property as a string, add quotes:
self.selectedUnitOrdinal = "4";
It's because when you get the unit.id it's returning a string not an integer. Objects in javascript store their keys as strings. So the only way to do it is your approach of surrounding 4 by quotations.
Edit
<select ng-model="ctrl.selectedUnitOrdinal" ng-options="convertToInt(unit.id) as unit.text for unit in ctrl.unitsOptions"></select>
$scope.convertToInt = function(id){
return parseInt(id, 10);
};
Just to add Christophe's answear: easiest way to achive and maintaint it is to make a directive:
JS:
.directive('convertToNumber', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$parsers.push(function(val) {
//saves integer to model null as null
return val == null ? null : parseInt(val, 10);
});
ngModel.$formatters.push(function(val) {
//return string for formatter and null as null
return val == null ? null : '' + val ;
});
}
};
});
Christophe's answear wont work correctly for '0' as it returns false on "val?" test.