本文翻译自:How to set focus on input field?

What is the 'Angular way' to set focus on input field in AngularJS? 在AngularJS中将焦点设置在输入字段上的“角度方式”是什么?

More specific requirements: 更具体的要求:

  1. When a Modal is opened, set focus on a predefined <input> inside this Modal. 打开模态后 ,将焦点放在此模态内的预定义<input>
  2. Everytime <input> becomes visible (eg by clicking some button), set focus on it. 每当<input>变为可见时(例如,通过单击某些按钮),请将焦点设置在它上面。

I tried to achieve the first requirement with autofocus , but this works only when the Modal is opened for the first time, and only in certain browsers (eg in Firefox it doesn't work). 我试图通过autofocus 达到第一个要求 ,但这仅在首次打开Modal时有效,并且仅在某些浏览器中有效(例如,在Firefox中不起作用)。

Any help will be appreciated. 任何帮助将不胜感激。


#1楼

参考:https://stackoom.com/question/10EpC/如何设置对输入字段的关注


#2楼

  1. When a Modal is opened, set focus on a predefined <input> inside this Modal. 打开模态后,将焦点放在此模态内的预定义<input>上。

Define a directive and have it $watch a property/trigger so it knows when to focus the element: 定义一个指令,并使其$ watch一个属性/触发器,以便它知道何时集中该元素:

Name: <input type="text" focus-me="shouldBeOpen">
app.directive('focusMe', ['$timeout', '$parse', function ($timeout, $parse) {return {//scope: true,   // optionally create a child scopelink: function (scope, element, attrs) {var model = $parse(attrs.focusMe);scope.$watch(model, function (value) {console.log('value=', value);if (value === true) {$timeout(function () {element[0].focus();});}});// to address @blesh's comment, set attribute value to 'false'// on blur event:element.bind('blur', function () {console.log('blur');scope.$apply(model.assign(scope, false));});}};
}]);

Plunker 柱塞

The $timeout seems to be needed to give the modal time to render. $ timeout似乎需要给定模态时间来渲染。

'2.' '2。 Everytime <input> becomes visible (eg by clicking some button), set focus on it. 每当<input>变为可见时(例如,通过单击某些按钮),请将焦点设置在它上面。

Create a directive essentially like the one above. 创建一个基本上与上述指令相似的指令。 Watch some scope property, and when it becomes true (set it in your ng-click handler), execute element[0].focus() . 观察一些scope属性,当它变为true时(在ng-click处理程序中进行设置),执行element[0].focus() Depending on your use case, you may or may not need a $timeout for this one: 根据您的用例,您可能需要也可能不需要$ timeout:

<button class="btn" ng-click="showForm=true; focusInput=true">show form andfocus input</button>
<div ng-show="showForm"><input type="text" ng-model="myInput" focus-me="focusInput"> {{ myInput }}<button class="btn" ng-click="showForm=false">hide form</button>
</div>
app.directive('focusMe', function($timeout) {return {link: function(scope, element, attrs) {scope.$watch(attrs.focusMe, function(value) {if(value === true) { console.log('value=',value);//$timeout(function() {element[0].focus();scope[attrs.focusMe] = false;//});}});}};
});

Plunker 柱塞


Update 7/2013 : I've seen a few people use my original isolate scope directives and then have problems with embedded input fields (ie, an input field in the modal). 更新7/2013 :我已经看到一些人使用我原来的隔离范围指令,然后在嵌入的输入字段(即模态中的输入字段)方面遇到问题。 A directive with no new scope (or possibly a new child scope) should alleviate some of the pain. 没有新作用域(或可能新的子作用域)的指令应减轻某些痛苦。 So above I updated the answer to not use isolate scopes. 因此,以上我更新了不使用隔离范围的答案。 Below is the original answer: 以下是原始答案:

Original answer for 1., using an isolate scope: 1.使用隔离范围的原始答案:

Name: <input type="text" focus-me="{{shouldBeOpen}}">
app.directive('focusMe', function($timeout) {return {scope: { trigger: '@focusMe' },link: function(scope, element) {scope.$watch('trigger', function(value) {if(value === "true") { $timeout(function() {element[0].focus(); });}});}};
});

Plunker . 柱塞 。

Original answer for 2., using an isolate scope: 2.使用隔离范围的原始答案:

<button class="btn" ng-click="showForm=true; focusInput=true">show form andfocus input</button>
<div ng-show="showForm"><input type="text" focus-me="focusInput"><button class="btn" ng-click="showForm=false">hide form</button>
</div>
app.directive('focusMe', function($timeout) {return {scope: { trigger: '=focusMe' },link: function(scope, element) {scope.$watch('trigger', function(value) {if(value === true) { //console.log('trigger',value);//$timeout(function() {element[0].focus();scope.trigger = false;//});}});}};
});

Plunker . 柱塞 。

Since we need to reset the trigger/focusInput property in the directive, '=' is used for two-way databinding. 由于我们需要在指令中重置trigger / focusInput属性,因此“ =”用于双向数据绑定。 In the first directive, '@' was sufficient. 在第一个指令中,“ @”就足够了。 Also note that when using '@' we compare the trigger value to "true" since @ always results in a string. 还要注意,当使用“ @”时,我们将触发值与“ true”进行比较,因为@始终会产生字符串。


#3楼

First, an official way to do focus is on the roadmap for 1.1 . 首先,官方的重点关注方法是1.1的路线图 。 Meanwhile, you can write a directive to implement setting focus. 同时,您可以编写指令以实现设置焦点。

Second, to set focus on an item after it has become visible currently requires a workaround. 其次,要在当前可见的项目上设置焦点,需要一种解决方法。 Just delay your call to element focus() with a $timeout . 只需使用$timeout延迟对元素focus()的调用即可。

Because the same controller-modifies-DOM problem exists for focus, blur and select, I propose having an ng-target directive: 因为在聚焦,模糊和选择方面存在相同的controller-modified-DOM问题,所以我建议使用ng-target指令:

<input type="text" x-ng-model="form.color" x-ng-target="form.colorTarget">
<button class="btn" x-ng-click="form.colorTarget.focus()">do focus</button>

Angular thread here: http://goo.gl/ipsx4 , and more details blogged here: http://goo.gl/4rdZa 此处的角度线程: http : //goo.gl/ipsx4 ,更多详细信息在此处发布: http : //goo.gl/4rdZa

The following directive will create a .focus() function inside your controller as specified by your ng-target attribute. 以下指令将在ng-target属性指定的控制器内部创建一个.focus()函数。 (It creates a .blur() and a .select() too.) Demo: http://jsfiddle.net/bseib/WUcQX/ (它.blur()创建一个.blur()和一个.select() 。)演示: http : //jsfiddle.net/bseib/WUcQX/


#4楼

I've written a two-way binding focus directive, just like model recently. 我写了一个双向绑定焦点指令,就像最近的模型一样。

You can use the focus directive like this: 您可以像这样使用focus指令:

<input focus="someFocusVariable">

If you make someFocusVariable scope variable true in anywhere in your controller, the input get focused. 如果您在控制器中的任何位置使someFocusVariable范围变量为true ,则输入将成为焦点。 And if you want to "blur" your input then, someFocusVariable can be set to false. 而且,如果您想“模糊”输入内容,可以将someFocusVariable设置为false。 It's like Mark Rajcok's first answer but with two-way binding. 这就像Mark Rajcok的第一个答案,但具有双向绑定。

Here is the directive: 这是指令:

function Ctrl($scope) {$scope.model = "ahaha"$scope.someFocusVariable = true; // If you want to focus initially, set this to true. Else you don't need to define this at all.
}angular.module('experiement', []).directive('focus', function($timeout, $parse) {return {restrict: 'A',link: function(scope, element, attrs) {scope.$watch(attrs.focus, function(newValue, oldValue) {if (newValue) { element[0].focus(); }});element.bind("blur", function(e) {$timeout(function() {scope.$apply(attrs.focus + "=false"); }, 0);});element.bind("focus", function(e) {$timeout(function() {scope.$apply(attrs.focus + "=true");}, 0);})}}});

Usage: 用法:

<div ng-app="experiement"><div ng-controller="Ctrl">An Input: <input ng-model="model" focus="someFocusVariable"><hr><div ng-click="someFocusVariable=true">Focus!</div>  <pre>someFocusVariable: {{ someFocusVariable }}</pre><pre>content: {{ model }}</pre></div>
</div>

Here is the fiddle: 这是小提琴:

http://fiddle.jshell.net/ubenzer/9FSL4/8/ http://fiddle.jshell.net/ubenzer/9FSL4/8/


#5楼

(EDIT: I've added an updated solution below this explanation) (编辑:我在此说明下方添加了更新的解决方案)

Mark Rajcok is the man... and his answer is a valid answer, but it has had a defect (sorry Mark)... 马克·拉杰科克(Mark Rajcok)是这个人...他的回答是有效的回答,但是 缺陷(对不起马克)...

...Try using the boolean to focus on the input, then blur the input, then try using it to focus the input again. ...尝试使用布尔将焦点放在输入上,然后使输入模糊,然后尝试使用它再次将输入聚焦。 It won't work unless you reset the boolean to false, then $digest, then reset it back to true. 除非将布尔值重置为false,然后将$ digest重置为true,否则它将不起作用。 Even if you use a string comparison in your expression, you'll be forced to change the string to something else, $digest, then change it back. 即使在表达式中使用字符串比较,也将不得不将字符串更改为$ digest,然后再将其更改。 (This has been addressed with the blur event handler.) (这已通过模糊事件处理程序解决。)

So I propose this alternate solution: 因此,我提出了这个替代解决方案:

Use an event, the forgotten feature of Angular. 使用一个事件,Angular的被遗忘的功能。

JavaScript loves events after all. JavaScript毕竟热爱事件。 Events are inherently loosely coupled, and even better, you avoid adding another $watch to your $digest. 事件本质上是松散耦合的,甚至更好的是,您避免在$ digest中添加另一个$ watch。

app.directive('focusOn', function() {return function(scope, elem, attr) {scope.$on(attr.focusOn, function(e) {elem[0].focus();});};
});

So now you could use it like this: 所以现在您可以像这样使用它:

<input type="text" focus-on="newItemAdded" />

and then anywhere in your app... 然后在您应用的任何位置...

$scope.addNewItem = function () {/* stuff here to add a new item... */$scope.$broadcast('newItemAdded');
};

This is awesome because you can do all sorts of things with something like this. 这很棒,因为您可以用这样的东西来做各种事情。 For one, you could tie into events that already exist. 首先,您可以绑定已经存在的事件。 For another thing you start doing something smart by having different parts of your app publish events that other parts of your app can subscribe to. 另一方面,您可以通过让应用程序的不同部分发布事件,让应用程序的其他部分可以订阅来开始做一些聪明的事情。

Anyhow, this type of thing screams "event driven" to me. 无论如何,这种事情对我来说是“事件驱动”的尖叫。 I think as Angular developers we try really hard to hammer $scope shaped pegs into event shape holes. 我认为,作为Angular开发人员,我们非常努力地将$ scope形的钉子锤入事件形状的孔中。

Is it the best solution? 这是最好的解决方案吗? I dunno. 我不知道。 It's a solution. 这是一个解决方案。


Updated Solution 更新的解决方案

After @ShimonRachlenko's comment below, I've changed my method of doing this slightly. 在@ShimonRachlenko在下面发表评论后,我已经稍微更改了执行此操作的方法。 Now I use a combination of a service and a directive that handles an event "behind the scenes": 现在,我结合使用服务和处理“幕后”事件的指令:

Other than that, it's the same principal outlined above. 除此之外,它与上面概述的原理相同。

Here is a quick demo Plunk 这是一个快速演示Plunk

Usage 用法

<input type="text" focus-on="focusMe"/>
app.controller('MyCtrl', function($scope, focus) {focus('focusMe');
});

Source 资源

app.directive('focusOn', function() {return function(scope, elem, attr) {scope.$on('focusOn', function(e, name) {if(name === attr.focusOn) {elem[0].focus();}});};
});app.factory('focus', function ($rootScope, $timeout) {return function(name) {$timeout(function (){$rootScope.$broadcast('focusOn', name);});}
});

#6楼

您还可以使用angular内置的jqlite功能。

angular.element('.selector').trigger('focus');

如何设置对输入字段的关注?相关推荐

  1. cleave.js_使用Cleave.js自动设置输入字段的格式

    考虑所有需要格式化结构的不同输入字段. 电话号码,信用卡,生日,街道地址--它们都有自己独特的模式 . 轻松保留这些字段并信任用户非常容易. 但是使用Cleave.js (一个免费的 原始 JavaS ...

  2. 从输入字段读取属性时,HTML编码丢失

    我正在使用JavaScript从隐藏字段中提取值并将其显示在文本框中. 隐藏字段中的值被编码. 例如, <input id='hiddenId' type='hidden' value='cha ...

  3. html5 规定输入字段,HTML5 Input属性详解

    本篇教程探讨了HTML5 Input属性详解,希望阅读本篇文章以后大家有所收获,帮助大家HTML5+CSS3从入门到精通 . < value 属性 value 属性规定输入字段的初始值: rea ...

  4. jquery editable ajax,使用X-editable jQuery库使用来自AJAX请求的数据填充Select2标记输入字段...

    我迫切需要JavaScript专家的一些帮助 . 我花了最近7个小时尝试了数百种代码组合,以获得基本的标签选择输入字段,以便与库 x-editable 和 select2 一起使用 . 我正在构建一个 ...

  5. ui字段和虚字段_绝无仅有!2019年最全的UI设计之输入字段剖析

    以下内容由摹客团队翻译整理,仅供学习交流,摹客iDoc是支持智能标注和切图的产品协作设计神器. 今天,我想谈谈UI设计中最常用的一个设计元素 - 输入字段.输入字段允许用户在UI中输入文本.它们通常出 ...

  6. 【Android】设置EditText输入类型和内容长度

    1.设置输入类型 设置EditText输入类型主要有两种方法,一种是使用EditText的setInputType()方法,另一种是在布局文件中使用android:inputType属性来设置. (1 ...

  7. Android设置EditText输入类型:setInputType()方法和android:inputType属性

    需求: 本次需求是做密码输入的隐藏.显示. 过程: 时间太久,很多属性已经记不太清楚了,比较纠结,所以整合下属性. 结果: 布局文件------------------------------ < ...

  8. 作为事件属性设置而输入的表达式“打开”产生如下错误:在Microsoft Office Access 与 OLE服务器或ActiveX控件通讯时出现问题。

    使用acess2010打开表时出错 作为事件属性设置而输入的表达式"打开"产生如下错误:在Microsoft Office Access 与 OLE服务器或ActiveX控件通讯时 ...

  9. 【Android NDK 开发】JNI 方法解析 ( C/C++ 设置 Java 对象字段 | 查找字段 | 设置字段 )

    文章目录 I . 设置 Java 对象 属性 流程 II . 查找 Java 对象属性 ( GetFieldID ) III . 设置 Java 对象属性 ( SetXxxField ) I . 设置 ...

最新文章

  1. 你需要知道的20个常用的Python技巧
  2. android getitem,android – ItemDecoration重写getItemOffsets()和动画
  3. Multiple classes found for path in the registry of this declarative base. Please use a fully
  4. 网站优化中受欢迎的文章是怎样的?
  5. 数据结构经典书籍--数据结构与算法分析
  6. Java黑皮书课后题第4章:*4.23(金融应用:酬金)编写一个程序,读取下面信息,然后输出一个酬金声明
  7. jarsigner签名过程
  8. ui测试怎么做?依据文档有哪些_微信小程序开发流程有哪些?各个环节注意事项...
  9. db4o官方入门教程翻译--06.集合和数组
  10. 奇瑞采用英伟达GPU,将实现L3自动驾驶
  11. 计算机毕业论文性能测试怎么写,计算机毕业论文撰写技巧
  12. basler相机详细使用说明
  13. mysql 归档_MySQL数据归档的几种操作方法介绍
  14. Word、WPS 文字背景颜色无法去除
  15. Android11编译导入PRODUCT_BOOT_JARS
  16. Parallel HDF5 简介
  17. 计算机网络nc是什么意思啊,请问nc是什么?
  18. Hive SQL复杂场景实现(1) —— 连续发单天数
  19. java笔记——反射
  20. HM2805B高效率恒流限流 WLED 驱动IC

热门文章

  1. SQL Server数据恢复准备之TRUNCATE TABLE理解
  2. jcseg 配置详解
  3. python 角度传感器模拟_Arduino300度模拟旋转角度传感器
  4. python图像处理:直方图的规定化(直方图匹配)
  5. Django基础-中文文档
  6. 浅谈Android Contacts数据库phone_lookup表的设计
  7. 以太坊系列 - 以太坊硬分叉和升级足迹
  8. 续——老机焕发青春——win8 ramos 的本地安装 (涉及vhd差分盘)
  9. 【Proteus仿真】51单片机过零检测触发控制光耦+可控硅调光电路
  10. 个人随笔/记录一个博友推荐的截图工具《FSCapture》