AngularJs set focus on input field after content is loaded

AngularJs set focus on input field after content is loaded

For example when the page is loaded you want to set focus on the first field but the jquery focus command is not working then you can try this version. Before that I tried;

  • $(“#myId”).focus() - NOT WORKED
  • - NOT WORKED

Then I tried another way to solve this issue because while lading page it couldnt set anything. So first we should load the page and than call the focus function

HTML CODE

<div ng-app="test">
   <div ng-controller="Ctrl">
      <body>
         <div>
            <input type="text" ng-model="input1" id="input1">
            <input type="text" ng-model="input2" id="input2">
            <input type="text" ng-model="input3" id="input3">
            <input type="text" ng-model="input4" id="input4">
         </div>
      </body>
      <!--We call it after our input fields are loaded.-->
      <div ng-init="focus()"></div>
   </div>
</div>

ANGULAR CODE - CoffeeScript

app = angular.module(‘test’, [])
app.controller 'Ctrl’, ($scope) ->
 $scope.input1 = “;
 $scope.input2 = ”;
 $scope.input3 = “;
 $scope.input4 = ”;

 setFocus= ->
   $(’#input4’).focus()

 $scope.focus = ->
   setTimeout setFocusOnPhone, 1000

*Yo need to use timeout because it might be your page is not loaded while you try to focus, so it is better to wait and call focus function.