在Angular上的Enter键上模糊输入字段 [英] Blur an input field on keypress enter on Angular
问题描述
我发现这个问题对于当有人按下"enter"键时提交表单:
I found this question very useful for submitting a form when someone presses the "enter" key:
JavaScript :
angular.module('yourModuleName').directive('ngEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if(event.which === 13) {
scope.$apply(function(){
scope.$eval(attrs.ngEnter, {'event': event});
});
event.preventDefault();
}
});
};
});
HTML:
<div ng-app="" ng-controller="MainCtrl">
<input type="text" ng-enter="doSomething()">
</div>
我想知道的是,当按下输入"键时,将字段设置为模糊. doSomething()
会使发件人字段模糊吗?
What I would like to do know, is to set the field to blur when the "enter" key is pressed. What would doSomething()
look like to blur the sender field?
我想保留ngEnter
指令,因为我想将其重新用于其他功能.
I would like to leave the ngEnter
directive as it is, since I would like to re-use it for other functions.
更新: 我知道我可以创建一个仅用于模糊处理的指令(现在就是这样),但是我想做的是能够执行以下操作:
Update: I know I can create a whole directive just for blurring (that's how I have it now), but what I'd like to do is be able to do something like this:
<input type="text" ng-enter="this.blur()">
或者如何将当前元素作为参数传递?
Or how do I pass the current element as a parameter?
<input type="text" ng-enter="doBlur(this)">
推荐答案
尝试了一堆东西之后,这似乎是不可能的,因为您需要传递$ event来获取目标元素,因此似乎使用了单独的指令唯一的方法:
After trying a bunch of things, this is seems not possible, as you would need to pass $event to get the target element, so separate directive seems to be the only way to go:
我们想要的:
您不能通过this
,因为它引用了作用域,因此您需要通过事件.
You cannot pass this
because it refers to the scope, so you need to pass the event.
<input type="text" ng-enter="doBlur($event)">
一旦有了事件,就可以从中获取目标.
Once you have the event, you can get the target from it.
$scope.doBlur = function($event){
var target = $event.target;
// do more here, like blur or other things
target.blur();
}
但是,您只能在类似ng-click ...的指令中获取pass事件,这还不能令人满意.如果我们可以将$ event传递给外部指令,则可以按照您要求的可重用方式进行模糊处理.
But, you can only get pass event in a directive like ng-click ... kinda unsatisfactory. If we could pass $event outside directive, we could blur in that reusable way you requested.
这篇关于在Angular上的Enter键上模糊输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!