Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Routes / input autofocus

I'm using angular route. Each page(route) has an input field. I have successfully used the attribute autofocus on the first page. When I navigate to the other pages, the input does not autofocus. Returning to the first page does not autofocus the input again. I understand now why it doesn't work but would like to know if there is a way to accomplish this.

I'm new to Angular and I'm not sure I understand what I read about ngFocus:

https://docs.angularjs.org/api/ng/directive/ngFocus

like image 793
odran037 Avatar asked Apr 29 '15 02:04

odran037


2 Answers

ngFocus is not what you're looking for. That directive is more of an event trigger. It will execute your code whenever the user gives focus to the textbox.

What you want is something like this custom directive:

angular
    .module('myApp')
    .directive('autofocus', function($timeout) {
        return {
            link: function(scope, element, attrs) {
                $timeout(function() {
                    element.focus();
                });
            }
        }
    });

Inspired by http://ericclemmons.com/angular/angular-autofocus-directive/

like image 92
Travis Collins Avatar answered Oct 24 '22 08:10

Travis Collins


In my case, the answer of Travis Collins did not work because somehow, the element was an array of inputs.

So I have to use the slightly modified version. Note, with arrow functions.

.directive('autofocus', ($timeout) => ({
    link: (scope, element: any, attrs) => {
        if (!element.focus && element.length) {
            element = element[0];
        }
        $timeout(() => {
            element.focus();
        });
    }
}));
like image 36
stefku Avatar answered Oct 24 '22 06:10

stefku