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

che*_*zer 12 javascript input autofocus angularjs angular-ng-if

当我环绕我input的时候ng-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>
Run Code Online (Sandbox Code Playgroud)

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

只需单击隐藏,然后在显示后,您将看到自动对焦不起作用!

Chrome中只在第一个节目上工作,在FFIE中它根本不起作用!

ug_*_*ug_ 16

问题是属性autofocus不是Angular指令.它是浏览器支持的<input>元素规范.如果您希望它在多个浏览器中按预期工作并且每次单击隐藏/显示时自动聚焦,您将需要制定指令.

我从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();
      });
    }
  }
}]);
Run Code Online (Sandbox Code Playgroud)
<!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>
Run Code Online (Sandbox Code Playgroud)