Pratik Kulshreshth
Pratik Kulshreshth

Reputation: 125

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.

Upvotes: 0

Views: 1933

Answers (2)

Viplock
Viplock

Reputation: 3319

As i can understand your issue.I can suggest try using "keyup" event on place of "keypress" event.

try this

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

Check this fiddle Here

Upvotes: 3

Rambler
Rambler

Reputation: 5482

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.

Upvotes: 1

Related Questions