AngularJS - Selects and ng-options
HTML
<script src="https://code.angularjs.org/1.3.1/angular.js"></script>
<div ng-app="myapp">
<fieldset ng-controller="Ctrl">
<select select-enhanced="" ng-model="selected" ng-options="item.value as item.name for item in options">
<option value="">Select a value</option>
</select>{{selected}}</fieldset>
</div>
JavaScript
angular.module('myapp', [])
.controller('Ctrl', function ($scope, $timeout) {
$scope.options = [{
name: 'One',
value: 10000
}, {
name: 'Two',
value: 20000
}, {
name: 'Three',
value: 30000
}];
// Invalid value that *should* get set correctly
// inside select-enhanced
$scope.selected = '20000';
$timeout(function () {
// Setting the model directly works fine
//$scope.selected = 20000;
});
})
.directive('selectEnhanced', ['$timeout', function ($timeout) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
ngModel.$formatters.push(function(modelValue) {
if (angular.isString(modelValue)) {
$timeout(function () {
ngModel.$setViewValue(parseInt(modelValue, 10));
});
}
return modelValue;
});
}
};
}]);