gpt4 book ai didi

javascript - AngularJS - 输入自动对焦与 ng-if 不工作

转载 作者:可可西里 更新时间:2023-11-01 02:03:59 25 4
gpt4 key购买 nike

当我用 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 指令。这是一个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>

关于javascript - AngularJS - 输入自动对焦与 ng-if 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36259939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com