TheKingPinMirza
TheKingPinMirza

Reputation: 8912

directive to convert decimal value to integer

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>

Upvotes: 3

Views: 2725

Answers (1)

Kashif Mustafa
Kashif Mustafa

Reputation: 1182

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();

        });
    }
};});

Upvotes: 2

Related Questions