简体   繁体   English

ng-init和onload之间的差异,用于函数调用[Angular JS]

[英]Difference between ng-init and onload for function invoke [Angular JS]

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. 我尝试了HTML5自动对焦,但由于存在浏览器兼容性问题,因此不得不为此寻找替代解决方案。

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. 我在Angular ng-initonload中具有以下函数以加载该函数。

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

onload is not in your angular context. onload不在您的角度范围内。 onload function is a callback function on LOAD event of DOM. onload函数是DOM的LOAD事件的回调函数。

your ng-init is in angular context. 您的ng-init在角度环境中。 You need to use angular ng-init. 您需要使用angular ng-init。

The ng-init function as shown in your code wont work as is. 代码中显示的ng-init函数无法按原样工作。 The function defined in ng-int should be in the angular context. ng-int中定义的函数应该在角度上下文中。 your focusOnInput() isn't in the angular context . 您的focusOnInput()不在角度上下文中。 It's in javascript context. 在javascript上下文中。

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 如果您想使用ng-init,则需要将$ window注入到控制器中,然后对$ scope使用assign focusOnInput并在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. 然后在您的ng-init中使用此myNewFunction。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM