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

AngularJS - input autofocus with ng-if not working

本文关键字:输入 ng 工作 如果不 AngularJS-      更新时间:2023-09-26

当我用ng-if包围我的input时,在隐藏和显示后,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>

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

只需点击隐藏,然后在节目中,你就会看到自动对焦不起作用!

中,Chrome仅在首秀中可用,在FFIE中根本不可用!

问题是属性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();
      });
    }
  }
}]);
<!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>

您可以为此使用指令。Plunker演示

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属性中定义其中的条件。

希望能有所帮助。

首先,您必须将div及其内容包装在body元素中。你在外面。请更正。

输入元素不应为空,有时可能不起作用。请添加更多属性,如名称type="text"或适当的属性。这是html5功能,应该以<!开头;!DOCTYPE html>

请注意:The autofocus attribute of the input tag is not supported in Internet Explorer 9 and earlier versions.访问此处了解更多详细信息