AngularJS - 使用ng-输入自动对焦,如果不起作用

时间:2016-03-28 09:59:04

标签: javascript angularjs input autofocus angular-ng-if

当我将inputng-if包围在一起时,隐藏并显示autofocus属性后生效:

以下是代码:

  <!DOCTYPE html>
<html ng-app>

  <head>
    <script data-require="angularjs@1.5.0" data-semver="1.5.0" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-init="view={}; view.show = true">
    <button ng-click="view.show = !view.show">{{view.show ? "hide" : "show"}}</button>
    <div ng-if="view.show">
      <input autofocus />
    </div>
  </body>
</html>

以下是吸虫: http://plnkr.co/edit/k7tb3xw5AsBYrhdlr3bA?p=preview

只需点击隐藏,然后点击显示,您就会看到自动对焦无效!

Chrome 仅适用于第一个节目,在 FF IE 中,它根本不起作用!

3 个答案:

答案 0 :(得分:16)

问题是属性autofocus不是Angular指令。这是一个browser supported specification of the <input> element。如果您希望在每个浏览器中按预期工作并且每次单击隐藏/显示时自动对焦,则需要制定指令。

我立即将此指令从Github Gist移除,归功于mlynch以构建此指令。

下面是你的应用程序的一个工作示例

angular  
    .module('App', [  
        'utils.autofocus',
    ]);
    
/**
 * the HTML5 autofocus property can be finicky when it comes to dynamically loaded
 * templates and such with AngularJS. Use this simple directive to
 * tame this beast once and for all.
 *
 * Usage:
 * <input type="text" autofocus>
 * 
 * License: MIT
 */
angular.module('utils.autofocus', [])

.directive('autofocus', ['$timeout', function($timeout) {
  return {
    restrict: 'A',
    link : function($scope, $element) {
      $timeout(function() {
        $element[0].focus();
      });
    }
  }
}]);
<!DOCTYPE html>
<html ng-app="App">

  <head  ng-init="view={}; view.show = true">
    <script data-require="angularjs@1.5.0" data-semver="1.5.0" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
  </head>

  <body>
    <button ng-click="view.show = !view.show">{{view.show ? "hide" : "show"}}</button>
  </body>
  
  <div ng-if="view.show">
    <input autofocus />
  </div>

    <script src="script.js"></script>
</html>

答案 1 :(得分:3)

您可以使用指令。 Plunker Demo

angular.module('myApp', []).directive('focusMe', function($timeout) {
    return {
        scope: {
            focusMeIf:"="
        },
        link: function ( scope, element, attrs ) {
            if (scope.focusMeIf===undefined || scope.focusMeIf) {
                $timeout( function () { element[0].focus(); } );
            }
        }
    };
});

您还可以在其中的focus-me-if属性中定义条件。

希望它有所帮助。

答案 2 :(得分:-1)

First of all you have to wrap the div and it's content inside the body element. You have it outside. please correct it.

Input element should not be blank and may not work sometimes. please add some more attribute like name and type="text" or appropriate. This is html5 feature and should start with <!DOCTYPE html>.

上的事件

Please Note : The autofocus attribute of the input tag is not supported in Internet Explorer 9 and earlier versions. visit here for more details