Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
985 views
in Technique[技术] by (71.8m points)

angularjs - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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() :
                        $element[0].blur();
                });
            });
        }
    }
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...