在angularjs中自动聚焦ng-repeat

Fiz*_*han 10 javascript autofocus angularjs

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

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

在控制器中

$scope.addPhone = function() {
    $scope.phones.add('');
}
Run Code Online (Sandbox Code Playgroud)

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

Kha*_* TO 19

尝试:

<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>
Run Code Online (Sandbox Code Playgroud)

JS:

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

    $scope.focusIndex = $scope.phones.length-1;
  }
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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.
               }
           });
         }
     };
})
Run Code Online (Sandbox Code Playgroud)

DEMO

  • 好的解决方案 最佳做法是,如果与未来角度版本发生冲突,不要使用ng作为自定义指令的前缀. (5认同)