gpt4 book ai didi

javascript - angularjs 中 ng-repeat 的自动对焦

转载 作者:可可西里 更新时间:2023-11-01 02:31:48 26 4
gpt4 key购买 nike

我使用 ng-repeat 获取多个电话号码

<div ng-repeat="phone in phones">
<input ng-model="phone" type="text" autofocus="autofocus">
</div>
<a ng-click="addPhone()">Add Phone</a>

在 Controller 中

$scope.addPhone = function() {
$scope.phones.add('');
}

每当我添加新手机时,它都会自动自动对焦输入。它很好用。但是当我重新加载(从链接打开) View 时,它会滚动到最后一个条目。我如何在第一次加载 View 时避免自动对焦。只有我想在添加新手机时自动对焦。

最佳答案

尝试:

<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>

JS:

$scope.addPhone = function() {
$scope.phones.push('Phone' + Math.random());

$scope.focusIndex = $scope.phones.length-1;
}

DEMO

使用自定义属性的解决方案:

<div ng-repeat="phone in phones">
<input ng-model="phone" type="text" custom-autofocus="$index == focusIndex" >
</div>
<a ng-click="addPhone()">Add Phone</a>

JS:

.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.
}
});
}
};
})

DEMO

关于javascript - angularjs 中 ng-repeat 的自动对焦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21350572/

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