2014-01-25 29 views
9

我采用NG-重复获得多个电话号码自动对焦在angularjs NG重复

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

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

回答

18

尝试:

​​

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

+5

很好的解决方案。最佳做法是在未来的角色版本发生冲突的情况下,不要用ng前缀自定义指令。 –

+0

@粗糙的兔子:这真是一个很好的观点。谢谢 –

+1

我刚刚用Chrome v52测试了这个解决方案(DEMO plunker link):我没有把注意力放在最后一个INPUT上......这个解决方案能否被淘汰? – Didier68

1

发生什么事是你有一个输入列表,要求页面在同一时间加载时的焦点。自上次输入渲染上次以来,它始终获取自动对焦。

解决方法是在需要时应用autofocus属性。

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

控制器:

$scope.addPhone = function() { 
    $scope.phones[$scope.phones.length-1].autofocus = 'false'; // unfocus the old 
    $scope.phones.add(''); 
    $scope.phones[$scope.phones.length-1].autofocus = 'true'; // focus the new 
} 
+0

这始终聚焦元素,即使表达式的值为“假”。使用Chrome。 –

+0

这不适用于Chrome –

+0

HTML中的布尔属性只有在它们不存在时才为false。 http://stackoverflow.com/a/25449778/41908 – Rob

0

在你的页面自动对焦多次并不被禁止,但不看的权利基础上,documentationm,https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input

它说Only one form element in a document can have the autofocus attribute

自动对焦HTML5此布尔属性允许您指定表单 在页面加载时应该有输入焦点,除非用户 覆盖它,例如通过键入不同的控件。文档中只有一个 表单元素可以具有自动聚焦属性,即 布尔值。如果将type属性设置为隐藏 (即无法将焦点自动设置为隐藏控件),则无法应用它。

我不会在ng-repeat内使用autofocus,并在添加后手动设置焦点。