自动对焦在angularjs NG重复 [英] Auto focus in ng-repeat in angularjs

查看:270
本文介绍了自动对焦在angularjs NG重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我采用NG-重复获得多个电话号码

I uses ng-repeat to get multiple phone numbers

<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('');
}

每当我添加新的手机,它会自动自动对焦的投入。它的伟大工程。但是,当我重​​新加载(从链路开放)来看,该滚动到最后一个条目。如何避免自动对焦在第一时间查看负荷。只有我要自动对焦,当我添加新的手机。

Whenever i add new phone, it automatically autofocus the input. It works great. But when i reload(open from link) the view, it scrolls to last entry. How do i avoid autofocus at first time the view loads. Only i want to autofocus when i add new phone.

推荐答案

尝试:

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

演示

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

Solution using custom attribute:

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

演示

这篇关于自动对焦在angularjs NG重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆