8

Simple focus is not working in angular

<div class="search pull-right tab-{{ showDetails2 }}" data-ng-click="showDetails2 = !showDetails2; showDetails = false; showDetails1 = false;searchFocus();">

html

<input type="text" data-ng-model="model.fedSearchTerm"
                    placeholder="New Search" required class="span12 fedsearch-box" />

MY function

$scope.searchFocus = function() {
            $('.fedsearch-box').focus();
        };
Prashobh
  • 9,216
  • 15
  • 61
  • 91

3 Answers3

15

I encountered the same issue. Solved it by enclosing the focus command inside $timeout. Make sure you pass the $timeout parameter in the .controller function.

$timeout(function() { $('.fedsearch-box').focus(); });
Jason Jan Ngo
  • 189
  • 1
  • 6
11

Here is a more robust implementation that works very well :

myApp.directive('focusMe', function () {
    return {
        link: function(scope, element, attrs) {
            scope.$watch(attrs.focusMe, function(value) {
                if(value === true) {
                    element[0].focus();
                    element[0].select();
                }
            });
        }
    };
});


<input type="text" ng-model="stuff.name" focus-me="true" />
bdavidxyz
  • 2,492
  • 1
  • 20
  • 40
  • 1
    This does work very well. Could you explain why the $watch is required to wrap the focus and select? I tried removing $watch and of course it doesn't work without it. – Markus Pint Aug 12 '15 at 12:17
1

You could write a directive for this purpose like;

myApp.directive('focus', function () {
  return function (scope, element, attrs) {
           element.focus();
  }
});

And in your HTML;

<input type="text" data-ng-model="model.fedSearchTerm"
                    placeholder="New Search" required focus />
BKM
  • 6,949
  • 7
  • 30
  • 45