Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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

More specific requirements:

  1. When a Modal is opened, set focus on a predefined <input> inside this Modal.

  2. Every time <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.

1 Answer

0 votes
by (106k points)

To set focus on input field on a predefined <input> inside this Modal define a directive and have it $watch a property/trigger so it knows when to focus the element:

Name: <input type="text" focus-me="shouldBeOpen">

app.directive('focusMe', ['$timeout', '$parse', function ($timeout, $parse) { 

return { 

link: function (scope, element, attrs) { 

var model = $parse(attrs.focusMe); 

scope.$watch(model, function (value) { 

console.log('value=', value); 

if (value === true) { 

$timeout(function () { 

element[0].focus(); 

    }); 

  } 

}); 

element.bind('blur', function () { 

console.log('blur');

scope.$apply(model.assign(scope, false));

    }); 

   } 

 };

}]);

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Aug 17, 2019 in Web Technology by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...