简体   繁体   English

单击Angular JS中的输入字段事件

[英]Click off input field event in Angular JS

Suppose you have an input field in an Angular JS app 假设您在Angular JS应用程序中有一个输入字段

 <input id="title" type="text" name="title" placeholder="enter a title" ng-model="item.title" />

I would like to display some feedback to the user about the validity of the input data AFTER the user has completed interacting with the input but I cannot think of a directive to watch the "click off" event. 我希望在用户完成与输入的交互之后向用户显示关于输入数据有效性的一些反馈,但我想不出有关观看“点击关闭”事件的指令。 That is, when a user types into the form, then either tabs next or clicks anywhere else. 也就是说,当用户键入表单时,可以选择下一个选项卡,也可以单击其他任何位置。

How do I capture the "click off and element" event. 如何捕获“click off and element”事件。

Please note, this is in contrast to an "off-click" event, where the event refers to when a user clicks anywhere BUT a given element. 请注意,这与“off-click”事件形成对比,其中事件是指用户点击给定元素的任何位置。

You need to use ng-blur directive. 您需要使用ng-blur指令。

ng-blur: NG-模糊:

Specify custom behavior on blur event. 指定模糊事件的自定义行为。

A blur event fires when an element has lost focus. 当元素失去焦点时会触发模糊事件。

Note: the print you see in the ng-blur is nothing but console.log using this for convenience, refer my fiddle! 注意: 你在ng-blur看到的打印只不过是console.log为方便起见,请参考我的小提琴!

JSFiddle Demo JSFiddle演示

JS: JS:

<div ng-controller='MyController' ng-app="myApp">
  <input id="title" type="text" name="title" placeholder="enter a title" ng-model="item.title" ng-blur="print('lost focus')" />
</div>

References: 参考文献:

  1. ng-blur NG-模糊

As mentioned in Naren's answer, ngBlur is the directive you are looking for. 正如Naren的回答中所提到的,ngBlur是您正在寻找的指令。

However, since you're trying to implement validation, you should know that angular has built-in validation functionality that will handle the events for you and using them is a better practice than reinventing the validation 'wheel'. 但是,由于您正在尝试实现验证,您应该知道angular具有内置验证功能,可以为您处理事件并使用它们比重新发明验证'wheel'更好。

Use validation directives like ngRequired, ngMinlength, ngMaxlength and ngPattern for simple validation needs. 使用ngRequired,ngMinlength,ngMaxlength和ngPattern等验证指令可以满足简单的验证需求。

https://docs.angularjs.org/guide/forms https://docs.angularjs.org/guide/forms

Use Angular UI's uiValidate directive for custom validation including validation through asynchronous http requests. 使用Angular UI的uiValidate指令进行自定义验证,包括通过异步http请求进行验证。

https://github.com/angular-ui/ui-validate https://github.com/angular-ui/ui-validate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM