AngularJS 中的 ng-repeat 自动对焦

2023-11-27

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

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

在控制器中

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

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


Try:

<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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AngularJS 中的 ng-repeat 自动对焦 的相关文章