Setting focus on an input field after ng-show

后端 未结 5 788
遥遥无期
遥遥无期 2020-12-13 13:41

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

5条回答
  •  轮回少年
    2020-12-13 14:23

    I have extended the answer to work with angular's ng-show and ng-hide

    app.directive('focusOnShow', function($timeout) {
        return {
            restrict: 'A',
            link: function($scope, $element, $attr) {
                if ($attr.ngShow){
                    $scope.$watch($attr.ngShow, function(newValue){
                        if(newValue){
                            $timeout(function(){
                                $element[0].focus();
                            }, 0);
                        }
                    })      
                }
                if ($attr.ngHide){
                    $scope.$watch($attr.ngHide, function(newValue){
                        if(!newValue){
                            $timeout(function(){
                                $element[0].focus();
                            }, 0);
                        }
                    })      
                }
    
            }
        };
    })
    

    All you need is to add attribute focus-on-show

    
    

提交回复
热议问题