Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting focus on an input field after ng-show

Is it possible set the focus of an input field via a controller once data has loaded (via $resource in this case)?

The input is hidden via ng-show until the data is returned from the API but I can't find a way to set the focus on the input. I know the ng-model name of the input, and the input name which means I could do it via jQuery, but I'd rather do it if possible the AngularJS way.

I've tried a lot of directive examples on here but they all seem to be pre-1.2 ng-focus, rely on a ng-click first from a button (can't happen in my case) or just don't work.
Any tips very gratefully received.

like image 427
Chris Southam Avatar asked Jun 25 '14 17:06

Chris Southam


People also ask

How can you specify focus in an input field?

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.

How do you know if input field is focused?

To check if an input field has focus with JavaScript, we can use the document. activeElement property to get the element in focus. to add an input. to check if the input element is focused.

What is Ng focus in AngularJS?

AngularJS ng-focus Directive The ng-focus directive tells AngularJS what to do when an HTML element gets focus. The ng-focus directive from AngularJS will not override the element's original onfocus event, both will be executed.


1 Answers

This is a simple directive that might work for you

<input focus-on="!!myResourceData" />  .directive('focusOn',function($timeout) {     return {         restrict : 'A',         link : function($scope,$element,$attr) {             $scope.$watch($attr.focusOn,function(_focusVal) {                 $timeout(function() {                     _focusVal ? $element[0].focus() :                         $element[0].blur();                 });             });         }     } }) 
like image 182
koolunix Avatar answered Sep 16 '22 14:09

koolunix