0

I have an angular app. Inside one controller I have a field for answers that is hidden. When a button is clicked using ng-click, that field is shown. I want to focus the cursor in that field. I have tried using:

document.getElementById("answer").focus();

but this doesn't work. However, when an answer is submitted some code is run and then the document.getElementById("answer").focus(); works.

The original function that shows the field is:

$scope.startStream = function () {
  $scope.showStream = true;
  document.getElementById("answer").focus();
};

Why does it not focus the cursor?

2
  • 2
    stackoverflow.com/questions/14833326/… stackoverflow.com/questions/24518994/… Commented Aug 12, 2015 at 10:20
  • 2
    As the comment above mentions, the way you are trying to do this is not how it is usually accomplished in Angular. You should go with another solution (from the links) to do this properly. As soon as you try to fetch elements from the DOM in your controller, you know something is not done right. Commented Aug 12, 2015 at 10:24

2 Answers 2

1

I understand that the question here is "why does it not focus the cursor".

It's because the template is processed by Angular after the whole function executes. And this is when showStream is picked up and the button appears. When you call document.getElementBy, the template is not yet processed and the button does not exist.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use a simple directive for this, assuming you want to use $scope.showStream:

angular.module('app')
    .directive('focusOnMe', function () {
        return {
            scope: {
                showStream: '='
            },
            link: function ($scope, $element, $attrs) {
                $scope.$watch('showStream', function () {
                    if ($scope.showStream) {
                        $element[0].focus();
                    }
                });
            }
        };
    });

Use like this:

<input type="text" ... focus-on-me="showStream" />

2 Comments

I don't know enough to upvote this. But I've certainly seen other directives and it does look like a better way than manipulating the DOM.
The idea of Angular is that DOM manipulation is driven by data, hence why directives are preferred vs selecting elements directly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.