3

So, I have the following Angular directive to autofocus first input field on the current page of my Ionic application. It works great when the first field isn't hidden. But, if it's hidden by ng-hide, logic fails. So need to modify the element selector to find just for visible elements in my directive.

angular.module('myApp').directive('focusMe', function($timeout) {
    return {
        link: function(scope, element, attrs) {
            $timeout(function() {
                element.find('label')[0].focus(); 
            }, 150);
        }
    };
});

Using above directive on a form element as follows,

<form name="signinForm" ng-submit="signinForm.$valid && doSignin(credentials)" novalidate focus-me>

So how should I change my jQLite find query to just look for the visible element? The find lookup is limited by tag name as per docs.

Thilina Sampath
  • 3,615
  • 6
  • 39
  • 65
Nirav Gandhi
  • 1,945
  • 1
  • 23
  • 32

1 Answers1

2

You can write something like this:

element[0].querySelector('input:not(.ng-hide)').focus();

jQLite only allows selecting by tag name. So we can use the pure Javascript version i.e. querySelector along with using :not selector.

See a working example below:

angular.module('myApp', [])
  .directive('focusMe', function($timeout) {
    return {
      link: function(scope, element, attrs) {
        $timeout(function() {
          element[0].querySelector('input:not(.ng-hide)').focus();
        }, 150);
      }
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<form focus-me ng-app="myApp">

  <input type="text" name="firstName" ng-show="false" />
  <input type="text" name="lastName" ng-show="true" />
  <input type="text" name="email" />

</form>
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
  • In my case, its not the input that has ng-hide class. An outer div has it. But this answers the question asked. Thanks. – Nirav Gandhi Dec 12 '15 at 08:24
  • Sure @NiravGandhi. You can similarly use the same with the outer `div` like so: `element[0].querySelector('div.foo:not(.ng-hide)').querySelector('input').focus();` where I'm assuming your parent `div` has a class `foo`. :-) – Shashank Agrawal Dec 12 '15 at 08:27