在AngularJS容易DOM操作 - 点击一个按钮,然后将焦点设置一个input元素 [英] Easy dom manipulation in AngularJS - click a button, then set focus to an input element

查看:238
本文介绍了在AngularJS容易DOM操作 - 点击一个按钮,然后将焦点设置一个input元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个角code:

<div class="element-wrapper" ng-repeat="element in elements">
  <div class="first-wrapper">
     <div class="button" ng-click="doSomething(element,$event)">{{element.name}}</div>   
  </div>
  <div class="second-wrapper">
    <input type="text" value="{{element.value}}">    
  </div>
</div>

我想会发生什么:当用户点击该按钮 - 输入元素将集中

What I want to happen: when the user clicks the button - the input element will be focused.

如何找到输入元素之后我点击按钮元素和重点呢?

我可以做的,看起来像这样一个功能:

I can do a function that looks like this:

function doSomething(element,$event) {
  //option A - start manipulating in the dark:
  $event.srcElement.parentNode.childNodes[1]

  //option B - wrapping it with jQuery:
   $($event.srcElement).closest('.element-wrapper').find('input').focus();
}

他们都没有工作 - 有一个更好的角度办法做到这一点?使用功能,如 .closest() .find()在jQuery的?

更新:

我发现这个技巧是工作的(但它仍然似乎不是正确的解决方案)

I found this hack to be working (but it still doesn't seem like the correct solution):

function doSomething(element,$event) {
   setTimeout(function(){
     $($event.srcElement).closest('.element-wrapper').find('input').focus();
   },0)
}

所以角完成所有的操作后,它的重点在input元素上我与的setTimeout包装它。

I am wrapping it with setTimeout so after Angular finishes all of its manipulations it focuses on the input element.

推荐答案

DOM操作应该是一条指令,而不是控制。我会定义一个 focusInput 指令,并使用它的按钮:

DOM manipulation should be in a directive instead of the controller. I would define a focusInput directive and use it on the button:

<div class="button" focus-input>{{element.name}}</div>   

指令:

app.directive('focusInput', function($timeout) {
  return {
    link: function(scope, element, attrs) {
      element.bind('click', function() {
        $timeout(function() {
          element.parent().parent().find('input')[0].focus();
        });
      });
    }
  };
});

Plunker

由于 jqLit​​e 是在DOM遍历方法方面相当有限,我不得不使用母公司()。父()。你不妨使用jQuery或一些JavaScript方法。

Since jqLite is rather limited in terms of DOM traversal methods, I had to use parent().parent(). You may wish to use jQuery or some JavaScript methods.

正如你已经发现,需要 $超时,使焦点()方法后被叫浏览器呈现(即处理完click事件)。

As you already found out, $timeout is needed so that the focus() method is called after the browser renders (i.e., finishes handling the click event).

找到('输入')[0] 让我们访问DOM元素,使我们能够使用JavaScript 焦点()方法(而不是找到('输入')。重点()这需要jQuery的)。

find('input')[0] gives us access to the DOM element, allowing us to use the JavaScript focus() method (rather than find('input').focus() which would require jQuery).

这篇关于在AngularJS容易DOM操作 - 点击一个按钮,然后将焦点设置一个input元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆