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>
2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.