Pratik Kulshreshth Pratik Kulshreshth - 5 months ago 19
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

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.