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?

Finnjon
  • 651
  • 4
  • 19
  • 2
    http://stackoverflow.com/questions/14833326/how-to-set-focus-on-input-field http://stackoverflow.com/questions/24518994/setting-focus-when-showing-a-form-input-in-angularjs – S Meaden Aug 12 '15 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. – Patrick Aug 12 '15 at 10:24

2 Answers2

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.

fdreger
  • 12,264
  • 1
  • 36
  • 42
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" />
Ahmed Nuaman
  • 12,662
  • 15
  • 55
  • 87