0

How to apply this jquery in Angular directive

Jquery

$(":input:not(input[type=button],input[type=submit],button):enabled:visible:first").focus();

I have tried the below but no luck

Angular Directive Link

.directive('autoFocus', ['$timeout', function ($timeout) {
  return {
    scope: {
      autoFocusInitial: "="
    },
    link: function (scope, element, attrs) {

      if (scope.autoFocusInitial == true) {

        $timeout(function () {
          element[0].querySelector("input:not(.ng-hide)").filter(":enabled:visible:first").focus();
        });
      }
    }

  };
}
klmuralimohan
  • 861
  • 4
  • 23
  • 44

1 Answers1

0

Your main problem is the visible and enabled,

var dom = $element[0].querySelector('input:not(.ng-hide):not(:disabled)');

Will not select any disabled elements, querySelector by default will only ever grab the first one, you cannot (with vanilla javascript by default) select based on the :visible pseudo.

DEMO WITH VISIBILITY CHECK: http://jsfiddle.net/Lvc0u55v/12386/

EDIT: As your comment suggested, you're after textarea and selects too, see my updated DEMO, however just a simple chain will suffice:

$element[0].querySelectorAll('input:not(:disabled), textarea:not(:disabled)');

Note: I removed the ng-hide as it now checks if it's visible or not, and seeing as ng-hide will be invisible it's pointless to add that to the request.

EDIT 2:

Seeing as you're wanting to bind the focus to dynamic generators such as an ng-repeat, I would conditionally tell the auto-focus when to run, IE when the ng-repeat has finished, in most cases, you should be able to run it without the ng-init or the condtion on the attribute.

DEMO: http://jsfiddle.net/Lvc0u55v/12393/ or http://jsfiddle.net/Lvc0u55v/12394/

Community
  • 1
  • 1
Shannon Hochkins
  • 11,763
  • 15
  • 62
  • 95
  • Thanks Hochkins. But this works only for input elements not text area or select elements. Assume we have all the elements in one form (input, text area and select drop down) whichever is enabled in first that should get focused. but in the above demo link is not working as expected. – klmuralimohan Nov 22 '16 at 10:30
  • this works great for static forms but not ng-repeat(dynamically created) input elements – klmuralimohan Nov 22 '16 at 10:57
  • Sorry but this is not what you asked for originally in the question, and you had no code to simulate otherwise, I would say it's your markup that's the problem not this directive because this will work anywhere, if you're inserting the inputs after the chain has already digested it will not work. – Shannon Hochkins Nov 22 '16 at 11:00
  • np.. thanks.. Here is sample, please have a look http://jsfiddle.net/Lvc0u55v/12392/ – klmuralimohan Nov 22 '16 at 11:06
  • Awesome... this works great... thanks a lot Hochkins! – klmuralimohan Nov 22 '16 at 11:18
  • no problems @klmuralimohan, don't forget to hit the tick to mark my answer as correct – Shannon Hochkins Nov 22 '16 at 11:22