Is there a way to reset an input field with AngularJS when the backspace or delete keys are pressed?
I've implemented this fantastic directive, and it's been working great, except for when the user uses the backspace or delete key to clear the field. In those cases, the validations prevent the form from being submitted (tested on Chrome v.50.0.2661.102).
I've attempted to make some adjustments to the directive without any luck. Any assistance would be greatly appreciated.
Here is the directive along with my modifications in the el.bind():
angular.module(myApp)
.directive('resetField',
function resetField($compile, $timeout) {
return {
require: 'ngModel',
scope: {},
transclusion: true,
link: function (scope, el, attrs, ctrl) {
var inputTypes = /text|search|tel|url|email|password/i;
if (el[0].nodeName !== "INPUT")
throw new Error("resetField is limited to input elements");
if (!inputTypes.test(attrs.type))
throw new Error("Invalid input type for resetField: " + attrs.type);
var template = $compile('<i ng-show="enabled" ng-mousedown="reset()" class="fa fa-times-circle"></i>')(scope);
el.addClass('reset-field');
el.after(template);
scope.reset = function () {
ctrl.$setViewValue(null);
ctrl.$render();
$timeout(function () {
el[0].focus();
}, 0, false);
scope.enabled = false;
};
el.bind('input', function () {
if (ctrl.$isEmpty(el.val())) {
scope.reset();
el[0].classList.remove('ng-dirty');
el[0].classList.remove('ng-touched');
el[0].classList.add('ng-pristine');
el[0].classList.remove('ng-invalid-required');
el[0].classList.add('ng-pristine');
el[0].classList.add('ng-valid');
} else {
scope.enabled = !ctrl.$isEmpty(el.val());
}
scope.$apply();
})
.bind('focus', function () {
$timeout(function () {
scope.enabled = !ctrl.$isEmpty(el.val());
scope.$apply();
}, 0, false);
})
.bind('blur', function () {
$timeout(function () {
scope.enabled = false;
}, 0, false);
});
}
};
};
);
The issue persists wherein html still displays ng-invalid-required because a related field that has been cleared using backspace isn't null.
If I'm triggering the same action as clicking on the "X", why does it behave differently?