Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto focus in ng-repeat in angularjs

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.

like image 826
Fizer Khan Avatar asked Jan 25 '14 12:01

Fizer Khan


People also ask

What is Ng-repeat in AngularJS?

AngularJS ng-repeat Directive The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.

What is focus in AngularJS?

AngularJS ng-focus DirectiveThe ng-focus directive tells AngularJS what to do when an HTML element gets focus. The ng-focus directive from AngularJS will not override the element's original onfocus event, both will be executed.


2 Answers

You can use this directive: https://github.com/aikus/ng-focus-if/blob/master/ng-focus-if.js For example:

<div ng-repeat="phone in phones">
   <input ng-model="phone" type="text" ng-focus-if="1==1"> 
</div>
<a ng-click="addPhone()">Add Phone</a>
like image 108
Nikita Avatar answered Sep 24 '22 17:09

Nikita


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

like image 39
Khanh TO Avatar answered Sep 23 '22 17:09

Khanh TO