Reputation: 9542
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
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
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
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