Chris Southam Chris Southam - 1 year ago 150
AngularJS Question

Setting focus on an input field after ng-show

Is it possible set the focus of an input field via a controller once data has loaded (via $resource in this case)?

The input is hidden via ng-show until the data is returned from the API but I can't find a way to set the focus on the input. I know the ng-model name of the input, and the input name which means I could do it via jQuery, but I'd rather do it if possible the AngularJS way.

I've tried a lot of directive examples on here but they all seem to be pre-1.2 ng-focus, rely on a ng-click first from a button (can't happen in my case) or just don't work.

Any tips very gratefully received.

Answer Source

This is a simple directive that might work for you

<input focus-on="!!myResourceData" />

.directive('focusOn',function($timeout) {
    return {
        restrict : 'A',
        link : function($scope,$element,$attr) {
            $scope.$watch($attr.focusOn,function(_focusVal) {
                $timeout(function() {
                    _focusVal ? $element[0].focus() :
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download