abhit
abhit

Reputation: 979

Focus not working in angularJS. angular.element(...).focus is not a function?

I have written the following lines to add focus on an input element in angular js:

angular.element(document.getElementById("chatinput")).focus();

but is not working an giving an error:

angular.element(...).focus is not a function

Upvotes: 0

Views: 5695

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123563

The "jqLite" library that's included with Angular for angular.element() doesn't include the .focus() method.

To make it available, you'll have to load the jQuery library before loading Angular and your application code. Once you've done that, angular.element() will be an alias of jQuery instead of jqLite.

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="/path/to/angular.js"></script>

Or, the Element returned from getElementById() has its own .focus() method that you can call without using angular.element():

document.getElementById("chatinput").focus();

// though, you may want to check that it's found first
var chatinput = document.getElementById("chatinput");
if (chatinput) chatinput.focus();

Upvotes: 3

Related Questions