我有一个想要异步获取的 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)器
。从技术上讲,您必须正确设计应用程序,这样就不需要重新编译。
关于javascript - 如何异步加载 Controller 并将其附加到 Angular 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37879500/