AngularJS: auto focus into input field when ng-show event is triggered
I came across the problem of setting the focus on input field when the field was shown conditionally by ng-show directive of AngularJS. I came up with following custom directive to solve the problem:
app.directive('showFocus', function($timeout) {
return function(scope, element, attrs) {
scope.$watch(attrs.showFocus,
function (newValue) {
$timeout(function() {
newValue && element.focus();
});
},true);
};
});
Usage:
<input type="text" ng-show="customcondition" show-focus="customcondition">Written by Bela Ezsias
Related protips
2 Responses
I can't get this to work. Plunkr http://plnkr.co/edit/SbOlCQMd4uiYCqz5u098?p=preview
over 1 year ago
·
Replacing the element with element[0] makes it working.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#