javascript 聚焦功能在角度不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18527087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:16:46  来源:igfitidea点击:

Focus function is not working in angular

javascriptangularjs

提问by Prashobh

Simple focus is not working in angular

简单的焦点在角度不起作用

<div class="search pull-right tab-{{ showDetails2 }}" data-ng-click="showDetails2 = !showDetails2; showDetails = false; showDetails1 = false;searchFocus();">

html

html

<input type="text" data-ng-model="model.fedSearchTerm"
                    placeholder="New Search" required class="span12 fedsearch-box" />

MY function

我的功能

$scope.searchFocus = function() {
            $('.fedsearch-box').focus();
        };

回答by Jason Jan Ngo

I encountered the same issue. Solved it by enclosing the focus command inside $timeout. Make sure you pass the $timeout parameter in the .controller function.

我遇到了同样的问题。通过将 focus 命令包含在 $timeout 中解决了这个问题。确保在 .controller 函数中传递 $timeout 参数。

$timeout(function() { $('.fedsearch-box').focus(); });

回答by bdavidxyz

Here is a more robust implementation that works very well :

这是一个更强大的实现,效果很好:

myApp.directive('focusMe', function () {
    return {
        link: function(scope, element, attrs) {
            scope.$watch(attrs.focusMe, function(value) {
                if(value === true) {
                    element[0].focus();
                    element[0].select();
                }
            });
        }
    };
});


<input type="text" ng-model="stuff.name" focus-me="true" />

回答by BKM

You could write a directive for this purpose like;

您可以为此目的编写指令,例如;

myApp.directive('focus', function () {
  return function (scope, element, attrs) {
           element.focus();
  }
});

And in your HTML;

在你的 HTML 中;

<input type="text" data-ng-model="model.fedSearchTerm"
                    placeholder="New Search" required focus />