javascript - 如何异步加载 Controller 并将其附加到 Angular 模块

标签 javascript jquery angularjs ajax

我有一个想要异步获取的 Controller ,它需要 Angular-cookies 库。

因此,我使用 jQuery 来获取并运行 Angular-cookies 库,然后使用 Controller 获取并执行该文件。我当前的代码如下:

$.getScript( "http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-cookies.min.js", function() {
  app.requires.push('ngCookies');
  $.getScript( "js/mailListCtrl.php", function() {
    console.log("Succesfully fetched controller mailListCtrl");
  });
});

这工作正常,并且两个脚本都在全局范围内运行,但是, Controller mailListCtrl 从未附加到我的模块。这是 mailListCtrl.js 的样子:

console.log("mailListCtrl.js is loaded"); // This is executed

app.controller('mailListCtrl', ['$http', '$timeout', '$cookies', '$scope', function ($http, $timeout, $cookies, $scope) {

  console.log("mailListCtrl is loaded, and code is executing"); // This is never executed

  // Lots of code...

}]);

所以我的问题是在初始页面加载后我无法将 Controller 附加到我的 Angular 模块。如果有人能解决这个问题,我将不胜感激。

最佳答案

听起来您需要手动引导您的应用程序。

$.getScript( "http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-cookies.min.js", function() {
  app.requires.push('ngCookies');
  $.getScript( "js/mailListCtrl.php", function() {
    console.log("Succesfully fetched controller mailListCtrl");

    var myAppDiv = angular.element("#divThatIsApp"); //in quotes should be the ID of the element where you have ngApp declared
    angular.bootstrap(myAppDiv, ["app"]); // in quotes should be your app name
  });
});

并从元素中删除ng-app。如果您需要重新编译特定 View ,那么您将不得不摆弄注入(inject)器。从技术上讲,您必须正确设计应用程序,这样就不需要重新编译。

这是一个good article about bootstrapping angular apps .

关于javascript - 如何异步加载 Controller 并将其附加到 Angular 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37879500/

相关文章:

javascript - Jquery keyup() 函数无法正常工作

Angularjs ng-show 不在模式内工作

javascript - JPA ng-repeat 过滤器 - 多个 id 作为一个

javascript - jQuery 选择没有类或 ID 的元素

javascript - 如何使用 Javascript 设置授权 HTTP header

jquery - 这个带有方括号和插入符号的 jQuery 代码是什么意思?

javascript - 在 ng-repeat 生成的 <ul> 列表中使用 ng-model

javascript - Webpack + @babel/preset-env 与动态导入... package.module 不被尊重?

javascript - Twilio:如果 <dial> 动词中的 "number"不是 "completed",则向用户发送消息

javascript - 使用 Ajax 从维基百科返回数据?