<select ng-model="model.id" convert-to-number> <option value="0">Zero</option> <option value="1">One</option> <option value="2">Two</option> </select> {{ model }}
angular.module('nonStringSelect', []) .run(function($rootScope) { $rootScope.model = { id: 2 }; })
.directive('convertToNumber', function() { return { require: 'ngModel', link: function(scope, element, attrs, ngModel) {
//format text from the user (view to model)
ngModel.$parsers.push(function(val) { return parseInt(val, 10); });
//format text going to user (model to view)
ngModel.$formatters.push(function(val) { return '' + val; }); } }; });
Formatters Definition
Array of functions to execute, as a pipeline, whenever the model value changes. Each function is called, in turn, passing the value through to the next. Used to format / convert values for display in the control and validation.
Parsers Definition
Array of functions to execute, as a pipeline, whenever the control reads value from the DOM. Each function is called, in turn, passing the value through to the next. Used to sanitize / convert the value as well as validation. For validation, the parsers should update the validity state using $setValidity(), and return undefined for invalid values.
To summarize:
- Formatters change how model values will appear in the view.
- Parsers change how view values will be saved in the model.