Based on this stackoverflow question here: How to set focus on input field?
I'm using the same Directive focuseMe
named focusSearch
in my example here: http://plnkr.co/edit/tdSxya?p=preview
However the input does not automatically gain focus as soon as the input is revealed.
- Step 1: Click the
Show Search
button - Step 2: The input should automatically get focused
<!-- <div class="search-input container-fluid"> -->
<div class="search-input" ng-show="showingSearchInput">
<input type="text"
class="form-control"
placeholder="Search"
ng-model="vh.searchInput"
ng-click="vh.searchPop($event)"
focus-search="showingSearchInput">
<div class="close-x-sml" ng-click="hideSearch()">(x)</div>
</div>
AngularJS code:
angular.module('app', [])
.directive('focusSearch', ['$timeout', '$parse', function($timeout, $parse) {
return {
link: function(scope, element, attrs) {
var model = $parse(attrs.focusMe);
scope.$watch(model, function(value) {
console.log('value=',value);
if (value === true) {
$timeout(function() {
element[0].focus();
});
}
});
// to address @blesh's comment, set attribute value to 'false'
// on blur event:
element.bind('blur', function() {
console.log('blur');
scope.$apply(model.assign(scope, false));
});
}
}
}])
.controller('sidebar',
['$scope',
'$rootScope',
'$timeout',
function($scope,
$rootScope,
$timeout) {
var vs = $scope;
$scope.clickedSearch = function() {
vs.showingSearchInput = true;
}
$scope.hideSearch = function() {
vs.showingSearchInput = false;
}
}]);