I am trying to create a directive to convert numeric value into integer.
For example, I have input type number and when user types 1.1 this value should be converted back to 1.
app.directive('toInteger', function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ngModel) {
ngModel.$parsers.push(function(value) {
var value = parseInt(value);
return value;
});
}
};
});
Where am I wrong?
Problem:
If i enter 1.1 than directive converts it back 1. However, it keeps on showing 1.1 on view (inside input field).
I am using directive with my html as follow
<input type="number" name="input" class="form-control" min="0" max="1000" data-ng-model="input" to-integer>
I have changed your directive, its working fine as per your requirement. Please use this
app.directive('toInteger', function ($parse) {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ngModel) {
ngModel.$parsers.push(function (value) {
var value = parseInt(value);
$parse(attrs.ngModel).assign(scope, value);
scope.$apply();
});
}
};});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With