klmuralimohan klmuralimohan - 16 days ago 6
AngularJS Question

How to enable first input focus in angular js directive

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();
});
}
}

};
}

Answer

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/