Input autofocus attribute

后端 未结 10 1520
Happy的楠姐
Happy的楠姐 2020-11-30 04:47

I have places in my code where I have this:


I would like to be able to use it like

相关标签:
10条回答
  • 2020-11-30 05:26

    so without $timeout you can also use auto focus like this -

        <input type="text" ng-show="{{condition}}" class='input-class'></input>
        angular.element(document).ready(function(){
        angular.element('.input-class')[0].focus();
        });
    
    0 讨论(0)
  • 2020-11-30 05:35

    Combining whar others mentioned above:

    JS Code:

    myApp.directive('ngAutofocus', ['$timeout', function ($timeout) {
        var linker = function ($scope, element, attrs) {
            $scope.$watch('pageLoaded', function (pageLoaded) {
                if (pageLoaded) {
                    $timeout(function () {
                        element[0].focus();
                    });
                }
            });
        };
    
        return {
            restrict: 'A',
            link: linker
        };
    }]);
    

    HTML:

      <input type="text" ng-model="myField" class="input-block-level edit-item" ng-autofocus>
    

    Set pageLoaded to true from your initial load method of the page get:

        var loadData = function () {
            ..
            return $http.get(url).then(function (requestResponse) {
               $scope.pageLoaded = true;
    ......
    }
    
    0 讨论(0)
  • 2020-11-30 05:36

    This directive should do the trick:

    angular.module('utils.autofocus', [])
    .directive('autofocus', ['$timeout', function($timeout) {
      return {
        restrict: 'A',
        scope: {'autofocus':'='}
        link : function($scope, $element) {
          $scope.$watch 'autofocus', function(focus){
            if(focus){
              $timeout(function() {
                $element[0].focus();
              });
            }
          }
        }
      }
    }]);
    

    Taken from here: https://gist.github.com/mlynch/dd407b93ed288d499778

    0 讨论(0)
  • 2020-11-30 05:38

    What I did is using regular autofocus on my inputs: <input autofocus>

    And then I set the focus on the first visible input with autofocus when angular is ready:

    angular.element(document).ready(function() {
      $('input[autofocus]:visible:first').focus();
    });
    

    Hope this helps.

    0 讨论(0)
提交回复
热议问题