AngularJS-如果不工作,则使用ng输入自动对焦
AngularJS - input autofocus with ng-if not working
当我用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仅在首秀中可用,在FF和IE中根本不可用!
问题是属性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.
访问此处了解更多详细信息
相关文章:
- 将输入值设置为ng模型属性[Angular]时出现问题
- 如何为动态创建的文本区域中输入的值更新ng模型
- 即使 ng 模型有值,也使输入字段为空
- 如何使用ng repeat中的选定输入更新我的对象
- 如何将ng消息与<输入名称='用户[名称]'>
- 删除ng模型中的ng模型输入值
- Angularjs:ng个重复元素的输入
- 如何验证使用 ng-repeat、ng-show(角度)动态创建的输入
- 调用时未输入角度 ng 单击函数
- 使用 ng-change 对输入类型数据进行 JavaScript 取消事件
- AngularJS输入ng模型未更新
- 断言var集通过<输入ng模型>不是未定义的
- 当输入ng-model是ngRepeat变量时,如何从输入数据中获取
- 价值的作用=“"在<输入ng模式>
- 我的数据绑定有效,但我的输入ng模型是't更新时更新
- AngularJS我正在尝试计算嵌套ng重复中包含的许多输入(ng模型)的结果
- AngularJS:在ng-if中输入ng-model不工作
- Angular -将两个输入ng模型合并为一个
- Angular的复选框输入ng-click从未被调用
- AngularJS:如何收听<输入ng变化>当使用Slider更改值时