Auto focus in ng-repeat in angularjs

Fizer Khan picture Fizer Khan · Jan 25, 2014 · Viewed 14.8k times · Source

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>

In controllers

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

Answer

Khanh TO picture Khanh TO · Jan 25, 2014

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

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

DEMO