Pratik Kulshreshth Pratik Kulshreshth - 1 year ago 71
AngularJS Question

Clear input field when a key is pressed in it

I tried to clear the input field on the keypress event in angularjs directive.

Html:

<input class="magic-input" type="number" ng-model="demo.input">


Directive:

.directive('magicInput', function () {
return {
restrict: 'C',
require: 'ngModel',
link: function (scope, elem, attrs, ngModel) {
elem.bind('keypress', function () {
ngModel.$setViewValue('');
ngModel.$render();
});
}
}
});


The problem here is that the directive clear current text but the pressed key remains in the input field.

here is the fiddle for this problem.

Answer Source

Chang your link function to the following :

 link: function (scope, elem, attrs, ngModel) {
    elem.bind('keypress', function (e) {
        ngModel.$setViewValue('');
        ngModel.$render(); 
        e.preventDefault();  //Note this
    });
}

e.preventDefault() will prevent the keypress event from completing.