【发布时间】:2016-05-24 21:37:31
【问题描述】:
当按下退格/删除键时,如何使用 Angularjs 重置输入字段?
我已经使用了这个awesome directive,它运行良好,除非用户使用退格键或删除键清除该字段。然后验证会阻止用户提交表单(使用 Chrome v.50.0.2661.102)。
我尝试修改指令,但没有成功。非常感谢任何帮助。
这是我在 el.bind() 中修改的指令:
angular.module(myApp)
.directive('resetField',
function resetField($compile, $timeout) {
return {
require: 'ngModel',
scope: {},
transclusion: true,
link: function (scope, el, attrs, ctrl) {
// limit to input element of specific types
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);
// compiled reset icon template
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 () {
//I added this snippet since the directive on its own works so
// well, (thought scope.reset() above would do the trick) but it
//doesn't pass the validations... thus the remaining code
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);
});
}
};
};
);
html 仍然显示 ng-invalid-required,因为已用退格键重置的依赖字段不为空。
如果我调用与单击“X”完全相同的调用,为什么它的功能不一样?
【问题讨论】:
标签: javascript angularjs validation field directive