Prashobh
Prashobh

Reputation: 9542

Focus function is not working in angular

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

Upvotes: 8

Views: 20876

Answers (3)

Jason Jan Ngo
Jason Jan Ngo

Reputation: 189

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

Upvotes: 15

bdavidxyz
bdavidxyz

Reputation: 2560

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" />

Upvotes: 11

BKM
BKM

Reputation: 7079

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 />

Upvotes: 1

Related Questions