0

I am working on a angular application and have a scenario where i want to focus on a text field on page load. i have tried HTML5 autofocus but have to find an alternative solution for this since there is a browser compatibility issue for the same.

I am planning to invoke a function on page load which will focus on the input field i wanted. I have the following functions with Angular ng-init and onload to load the function.

I am not sure which method should i follow in the angular context as i am little confused between their difference.

onload

    <body onload="focusOnInput()">
       <form name="resetPasswordForm">
          <input name="NewPassword" type="password"/>
       </form>
    </body>
    <script>
       function focusOnInput() {
          document.forms["resetPasswordForm"]["NewPassword"].focus();
       }
    </script>

Angular ng-init

    <body in-init="focusOnInput()">
       <form name="resetPasswordForm">
          <input name="NewPassword" type="password"/>
       </form>
       <script>
          function focusOnInput() {
             document.forms["resetPasswordForm"]["NewPassword"].focus();
          }
       </script>
    </body>
Sha
  • 1,826
  • 5
  • 29
  • 53
  • 3
    Possible duplicate of [Difference between onLoad and ng-init in angular](http://stackoverflow.com/questions/18441775/difference-between-onload-and-ng-init-in-angular) – Sajeetharan Jan 11 '17 at 05:41
  • What is the difference between init and load on page life cycle? that is the answer – Ramesh Rajendran Jan 11 '17 at 05:41

1 Answers1

0

onload is not in your angular context. onload function is a callback function on LOAD event of DOM.

your ng-init is in angular context. You need to use angular ng-init.

The ng-init function as shown in your code wont work as is. The function defined in ng-int should be in the angular context. your focusOnInput() isn't in the angular context . It's in javascript context.

if you like to use ng-init you'll need to inject $window into your controller and then use assign focusOnInput to your $scope and use that method in ng-init

something like this

angular.module().controller('TestController',['$scope','$window',function($scope,$window){

 ......

 $scope.myNewFunction = $window.focusOnInput;

 ......



}])

and then use this myNewFunction in your ng-init.

Bhavik Shah
  • 358
  • 4
  • 11