initialize angular on window.onload event

杀马特。学长 韩版系。学妹 提交于 2020-01-11 12:26:25

问题


In a thirth party framework, A html page can be modified by providing javascript code that will be added by the framework to the window onload. From their content can be written to the AddIn div element.

How could I inject a angular application into this div element (HTML + js).

<!DOCTYPE html>
<html>
  <head>
    <script src="http://apps.bdimg.com/libs/angular.js/1.4.0-beta.4/angular.min.js"></script>
    <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script type="text/javascript">
      window.onload=function() { 
        //todo add js code here
      }
      </script>
  </head>
  <body>
    <div id="AddIn"></div>
  </body>
</html>

I can add the html

$('#AddIn').append("<div ng-app='dropboxApp' ng-controller='dropboxController as dropbox'>{{dropbox.label}}</div>");

but I am not sure where to add my angular init code, and get things working

angular.module('dropboxApp', [])
                .controller('dropboxController', function () {
                    var dropbox = this;
                    dropbox.label = 'hello angular';
                });

回答1:


You could lazily initialize your app on the page instead of using ng-app directive on page. After you html injection you could initialize angular on your page using angular.bootstrap method basically which takes DOM & then inside array it needs module name.

While doing this you need to add your all the angular component files on the page itself after angular reference. They should be initialized before you bootstrap the app on the page.

window.onload=function() { 
    $('#AddIn').append("<div ng-controller='dropboxController as dropbox'>{{dropbox.label}}</div>");
    //add angular html first
    //then run angular on the page using angular.bootstrap.
    angular.bootstrap($('#AddIn'), ['demo']);
}

Note: Load jQuery before angular to get jQuery compiled DOM instead of get jQLite compiled DOM.




回答2:


In addition to the Pankaj answer, you can use the Angular $window

$window.onload = function (){}


来源:https://stackoverflow.com/questions/33352773/initialize-angular-on-window-onload-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!