0

I have a ng-repeat with input box in each repeated item. I have set the autofocus to input.

<input type="text" autofocus />

So autofocus will be applied to all items. However, there's a bug in iOS where the last input box is auto focused instead of the first one.

I need to set it to return true based on the condition as in:

<input autofocus="{{$first  ? 'true' : 'false' }}" >

Any idea how to accomplish this with Angular?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Nima
  • 2,100
  • 2
  • 23
  • 32
  • `$first ? 'true' : 'false'` can just be shortened to `$first`; don't use the string representations of `'true'` and `'false'`. – msanford Jul 31 '17 at 13:13

1 Answers1

0

Use a custom directive to focus an element

Directive

app.directive('autofocus', ['$timeout', function($timeout) {
  return {
    restrict: 'A',
    link : function(scope, element,attrs) {
       $timeout(function() {
       if(attrs.autofocus==='true'){
        element[0].focus();
       }
      });
    }
  }
}]);

Controller

app.controller('MainCtrl', function($scope) {
  $scope.names = ['first','second','third','fourth','fifth'];
});

HTML

 <div ng-repeat="name in names">
    <input type="text" autofocus="{{$index==0}}" ng-model="name" />
    </div>

Demo plunker link

himanshu
  • 188
  • 2
  • 16