1

I have an input element being created in an AngularJS directive:

<span ng-repeat="phrasePart in phraseParts">
    {{phrasePart}}<input ng-attr-id="{{ 'phrasePart-' + $index }}" ng-if="!$last"/>
</span>

and I want the first input element i.e. (<input id="phrasePart-0" /> to receive focus, so I do this with jQuery:

$(function () {
    $("#phrasePart-0").focus();
});

However, this code does set focus in an input element that is directly in the HTML and not rendered by AngularJS.

  • How can I get jQuery to wait until the input element "phrasePart-0" is created by AngularJS before setting focus?
  • Is there an "AngularJS way" to set focus that would be better?

3 Answers 3

2

The more 'Angular' way to do it would to use a directive.

then apply that directive to the first occurance as a class

Just checked this. This is not the case because ng-class does not recompile dom elements for angular directives.

Instead, this may be a more reliable solution: http://jsfiddle.net/HB7LU/9958/

.directive("focusme", function(){
  return {
      scope:{
          focusme:"="
      },
    link:function(scope, element, attrs, $timeout){
        if (scope.focusme){
            element[0].focus();
        }
    }
  }
})

and for the HTML

 <span ng-repeat="phrasePart in phraseParts">
        {{phrasePart}}<input ng-attr-id="{{ 'phrasePart-' + $index }}" ng-if="!$last" focusme="$first" />
    </span>
Sign up to request clarification or add additional context in comments.

2 Comments

Ammended. ng-class does not call $compile which means the 'directive' class won't do anything.
I also like this approach more than using $timeout. It also seems to work using HTML5 autofocus attribute, changing 'element[0].focus();' to 'element[0].autofocus = true;', which is cool. Still, the fiddle doesn't work under Firefox for me :/
2

Use, $timeout

Check out this fiddle

http://jsfiddle.net/cndhpqrz/

var myApp = angular.module('myApp',[]);

function myfunc($scope, $timeout)
{

$scope.phraseParts=[1,2,3,4,5,6];

$timeout(function()
         {
    $("#phrasePart-2").focus();
});
}

2 Comments

Interesting, both your fiddle and my code don't work in Firefox, but work in Chrome.
They both work in IE11 as well. Do they work in your Firefox?
0

use $timeout service of angularjs.

$timeout handler will be called after the digest cycle completes. So at that time you will have your input rendered.

$timeout(function () {
    $("#phrasePart-0").focus();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.