Reputation: 718
I don't get how I can focus the input after it appears with ng-show / ng-hide. I'm using a button with ng-click="showme=!showme"
to show and hide my input. Any tips?
HTML:
<div ng-app="">
<button ng-click="showme=!showme">SHOW/HIDE</button>
<div class="wrapper">
<p ng-hide="showme">It will appear here!</p>
<input ng-show="showme" type="text" name="s" placeholder="Search..." />
</div>
</div>
I tryed using what is suggested here, but it doesn't work.
I also tryed the autofocus directive, but it still doesn't work.
Upvotes: 0
Views: 1292
Reputation: 718
I've fixed this adding a controller in which I declare a new scope and an a toggling on the attribute that declares the focus. Here is the code:
HTML:
<div ng-app="pippo" ng-controller="pippoctrl">
<button ng-click="showme=!showme;shouldBeOpen=!shouldBeOpen">SHOW/HIDE</button>
<div class="wrapper">
<p ng-hide="showme">It will appear here!</p>
<input focus-me="shouldBeOpen" ng-show="showme" type="text" name="s" placeholder="Search..." />
</div>
</div>
JS:
var app=angular.module("pippo",[]);
app.controller('pippoctrl', ['$scope',function ($scope){
$scope.shouldBeOpen=false;
}]);
app.directive('focusMe', ['$timeout' , function ($timeout) {
return {
//scope: true, // optionally create a child scope
link: function (scope, element, attrs) {
console.log('focus-me=', attrs.focusMe);
scope.$watch(attrs.focusMe,function(value){
console.log('value=', value);
if (value === true) {
$timeout(function () {
element[0].focus();
});
}
});
}
};
}]);
Here is the full code: JSFiddle
Upvotes: 1