Nirav Gandhi
Nirav Gandhi

Reputation: 2005

How do you find first visible element with jqlite under AngularJS?

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.

Upvotes: 3

Views: 1654

Answers (1)

Shashank Agrawal
Shashank Agrawal

Reputation: 25797

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>

Upvotes: 2

Related Questions