我有一个想要异步获取的控制器,这需要angular-cookies库。
因此我使用jQuery来获取并运行angular-cookies库,然后使用控制器获取并执行该文件。我目前的代码如下:
$.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");
});
});
这项工作正常,两个脚本都在全局范围内运行,但是,控制器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...
}]);
所以我的问题是在初始页面加载后我无法将控制器连接到我的角度模块。如果有人能解决这个问题,我将非常感激。
答案 0 :(得分:0)
听起来您需要手动Bootstrap
您的应用。
$.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
。如果您需要重新编译特定视图,则必须使用injector
。从技术上讲,您必须正确设计您的应用程序,这样您就不需要重新编译了。
答案 1 :(得分:0)
解决方案实际上非常简单。由于很久以前我不记得从哪里得到这个,但是将这段代码添加到app.config
可以在角度模块的初始引导后连接控制器:
app.controller = function( name, constructor ) {
$controllerProvider.register( name, constructor );
return( this );
};
注意:请记住将$controllerProvider
作为app.config