How to set focus on input field?

2018-12-31 02:50发布

What is the 'Angular way' to set focus on input field in AngularJS?

More specific requirements:

  1. When a Modal is opened, set focus on a predefined <input> inside this Modal.
  2. Everytime <input> becomes visible (e.g. by clicking some button), set focus on it.

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 (e.g. in Firefox it doesn't work).

Any help will be appreciated.

30条回答
像晚风撩人
2楼-- · 2018-12-31 03:48

You can also use the jqlite functionality built into angular.

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

查看更多
忆尘夕之涩
3楼-- · 2018-12-31 03:48

This works well and an angular way to focus input control

angular.element('#elementId').focus()

This is although not a pure angular way of doing the task yet the syntax follows angular style. Jquery plays role indirectly and directly access DOM using Angular (jQLite => JQuery Light).

If required, this code can easily be put inside a simple angular directive where element is directly accessible.

查看更多
笑指拈花
4楼-- · 2018-12-31 03:48

A simple one that works well with modals:

.directive('focusMeNow', ['$timeout', function ($timeout)
{
    return {
        restrict: 'A',

        link: function (scope, element, attrs)
        {


            $timeout(function ()
            {
                element[0].focus();
            });



        }
    };
}])

Example

<input ng-model="your.value" focus-me-now />
查看更多
浮光初槿花落
5楼-- · 2018-12-31 03:48

The following directive did the trick for me. Use the same autofocus html attribute for input.

.directive('autofocus', [function () {
    return {
        require : 'ngModel',
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.focus();
        }
    };
}])
查看更多
时光乱了年华
6楼-- · 2018-12-31 03:49

Probably, the simplest solution on the ES6 age.

Adding following one liner directive makes HTML 'autofocus' attribute effective on Angular.js.

.directive('autofocus', ($timeout) => ({link: (_, e) => $timeout(() => e[0].focus())}))

Now, you can just use HTML5 autofocus syntax like:

<input type="text" autofocus>
查看更多
梦寄多情
7楼-- · 2018-12-31 03:50

Just throwing in some coffee.

app.directive 'ngAltFocus', ->
    restrict: 'A'
    scope: ngAltFocus: '='
    link: (scope, el, attrs) ->
        scope.$watch 'ngAltFocus', (nv) -> el[0].focus() if nv
查看更多
登录 后发表回答