Javascript 在ng中自动对焦在angularjs中重复
我使用ng repeat获取多个电话号码Javascript 在ng中自动对焦在angularjs中重复,javascript,angularjs,autofocus,Javascript,Angularjs,Autofocus,我使用ng repeat获取多个电话号码 <div ng-repeat="phone in phones"> <input ng-model="phone" type="text" autofocus="autofocus"> </div> <a ng-click="addPhone()">Add Phone</a> 每当我添加新手机时,它会自动聚焦输入。它工作得很好。但当我重新加载(从链接打开)视图时,它会滚动到最后一个条
<div ng-repeat="phone in phones">
<input ng-model="phone" type="text" autofocus="autofocus">
</div>
<a ng-click="addPhone()">Add Phone</a>
每当我添加新手机时,它会自动聚焦输入。它工作得很好。但当我重新加载(从链接打开)视图时,它会滚动到最后一个条目。如何避免在首次加载视图时自动聚焦。当我添加新手机时,我只想自动对焦。当页面同时加载时,您有一个需要对焦的输入列表。由于最后一个输入最后渲染,因此它始终获得自动聚焦 解决方案是在需要时应用
自动聚焦
属性
<div ng-repeat="phone in phones">
<input ng-model="phone" type="text" autofocus="{{phone.autofocus || 'false'}}">
</div>
<a ng-click="addPhone()">Add Phone</a>
尝试:
使用自定义属性的解决方案:
<div ng-repeat="phone in phones">
<input ng-model="phone" type="text" custom-autofocus="$index == focusIndex" >
</div>
<a ng-click="addPhone()">Add Phone</a>
在您的页面中多次自动对焦并不是禁止的,但从文档来看,这并不正确 它表示文档中只有一个表单元素可以具有自动聚焦属性 自动聚焦HTML5此布尔属性允许您指定 控件应该在页面加载时具有输入焦点,除非用户 重写它,例如通过键入其他控件。只有一个 文档中的表单元素可以具有自动聚焦属性,即 布尔值。如果“类型”属性设置为“隐藏”,则无法应用该属性 (即,无法自动将焦点设置为隐藏控件)
我不希望在
ng repeat
中使用autofocus
,并在添加后手动设置焦点。您可以使用此指令:
例如:
<div ng-repeat="phone in phones">
<input ng-model="phone" type="text" ng-focus-if="1==1">
</div>
<a ng-click="addPhone()">Add Phone</a>
添加电话
很好的解决方案。最好的做法是不要在自定义指令前面加ng,以防与未来的angular版本发生冲突。我刚刚用Chrome v52测试了这个解决方案(演示plunker链接):我没有把重点放在最后的输入上。。。这个解决方案会过时吗?@Didier68:只有在添加新手机时,你才能获得关注。如果您想将焦点放在页面加载上,则需要将默认索引设置为focusIndex
:而不是使用condition custom autofocus=“$index==focusIndex”,只需使用custom autofocus=“$last”@user626710:在这种情况下,您的方法很好,但使用focusIndex
是一种更为通用的方法。这总是聚焦元素,即使表达式的计算结果为“false”。在HTML中使用Chrome.Boolean属性只有在不存在时才为false。
<div ng-repeat="phone in phones">
<input ng-model="phone" type="text" ng-if="$index == focusIndex" autofocus>
<input ng-model="phone" type="text" ng-if="$index != focusIndex">
</div>
<a ng-click="addPhone()">Add Phone</a>
$scope.addPhone = function() {
$scope.phones.push('Phone' + Math.random());
$scope.focusIndex = $scope.phones.length-1;
}
<div ng-repeat="phone in phones">
<input ng-model="phone" type="text" custom-autofocus="$index == focusIndex" >
</div>
<a ng-click="addPhone()">Add Phone</a>
.directive('customAutofocus', function() {
return{
restrict: 'A',
link: function(scope, element, attrs){
scope.$watch(function(){
return scope.$eval(attrs.customAutofocus);
},function (newValue){
if (newValue === true){
element[0].focus();//use focus function instead of autofocus attribute to avoid cross browser problem. And autofocus should only be used to mark an element to be focused when page loads.
}
});
}
};
})
<div ng-repeat="phone in phones">
<input ng-model="phone" type="text" ng-focus-if="1==1">
</div>
<a ng-click="addPhone()">Add Phone</a>