Is there a way to display a textarea
in Angular based on the value of a preview
variable? Once the value of preview
is set to true, I want to automatically focus on the textarea
.
Controller Logic
.controller('MyCtrl', ['$scope', function ($scope) {
$scope.preview = false;
$scope.showPreview = function() {
$scope.preview = true;
}
}])
Directive Logic
.directive('previewFocus', function() {
return function(scope, element, attrs) {
scope.$watch('preview',
function (newValue) {
newValue && element[0].focus();
},true);
};
});
Next, there is a div
that triggers the showPreview()
method when clicked:
<div ng-click="showPreview()">Add Post</div>
Followed by a textarea
with the preview-focus
directive:
<textarea class="previewInput" preview-focus></textarea>
I have checked the code and everything seems to be running correctly, including the callback on the scope.$watch
function. However, the textarea
does not receive focus. The focus works fine when the ngShow
directive is not used. Here are two JSFiddle examples illustrating both scenarios.
Focus does not work: JSFiddle with ngShow
Focus works fine: JSFiddle without ngShow
Is there a proper way to utilize ngShow
and still focus on the displayed element simultaneously?