简体   繁体   English

Angular 1.x专注于输入字段仅工作一次

[英]Angular 1.x focus on input field works only once

I have a search page on a web / mobile app which has an field. 我在一个包含字段的网络/移动应用程序上有一个搜索页面。 When we get on the page, focus must be set on that field so the user can simply just start typing. 当我们进入页面时,必须将焦点设置在该字段上,以便用户可以简单地开始输入。 I have created a directive and linked it to my input field, but it works only once I visit the page with a fresh cache. 我已经创建了一条指令并将其链接到我的输入字段,但是只有当我使用新的缓存访问该页面时,该指令才起作用。 When you visit the page with a mobile device, the keyboard comes up the first time, and after that, you see it come up and go immediately down after. 当您使用移动设备访问该页面时,键盘第一次出现,然后,您会看到它出现,然后立即下移。 It seems like the input field has the focus only for half a second. 似乎输入字段仅具有半秒钟的焦点。 I have tried several answers to this problem, but nothing solved it. 我已经尝试过对这个问题的几个答案,但是没有任何解决方案。

Directive: 指示:

app.directive('focusField',function($timeout) {
return {
  link : function($scope,$element,$attr) {
    $scope.$watch($attr.focusField,function(val) {
        $timeout(function() {
            val ? $element[0].focus() :
                $element[0].blur();
        });
    });
  }
}});

HTML: HTML:

<input id="search-field" class="form-control" ng-model="searchText" placeholder="Search interviews..." focus-field='true' />

I have also tried to set focus in the controller by using $('#search-field').focus(); 我也试图通过使用$('#search-field')。focus();在控制器中设置焦点。 but it has the exact same issue. 但它有完全相同的问题。

Any ideas on how I can force the focus on the field every time the user visits? 关于如何在每次用户访问时如何强制将重点放在该领域上的任何想法?

Thanks in advance! 提前致谢!

If the input needs to be focused, why would you need focus-field='false' . 如果需要重点关注输入,为什么要需要focus-field='false' If I were you, I would simply remove the $attr , and the $watcher . 如果我是您,则只需删除$attr$watcher

link : function($scope,$element) {
    $timeout(function() {
        $element[0].focus();
    }, 0);
};

Then go for 然后去

<input focus-field type="search" />

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

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