我想在 AngularJS 启动后添加依赖项。我尝试按照这篇文章 ( re-open and add dependencies to an already bootstrapped application ) 中的建议通过 app.requires.push('app.main');
来完成。但是,它不起作用。
这是我的示例代码:
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="https://code.angularjs.org/1.4.3/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
</body>
</html>
脚本.js
var app = angular
.module('app',[])
.run(function($http){
$http.get("script2.js").success(function(data){
eval(data);
//app.requires.push('app.main');
}).error(function(){
alert("error");
});
});
脚本2.js
alert("it's loaded");
angular.module('app.main', [])
.run(function(){
alert("it's running");
});
console.log(app);
app.requires.push('app.main');
http://plnkr.co/edit/gN2kkoyqamB4OANXMUjA
为什么它不起作用?我该如何解决?
最佳答案
moduleName.requires
没有记录,理解不多并且 used only by Angular injector .反过来,注入(inject)器在引导过程中被调用(通过 ng-app
或 angular.bootstrap
)或使用 angular.injector
创建新的注入(inject)器。
一旦应用程序被引导并且配置/运行阶段结束,新的配置/运行 block 就不能被调用。同样涉及 moduleName.directive
、moduleName.controller
和其他模块方法,所有这些方法都应该在应用程序启动之前调用。因此,它们不适合异步定义模块。
新定义的运行 block 可以被调用by creating an injector explicitly (这意味着创建了一个新的应用程序实例):
var newApp = angular.injector(['app.main']);
它的主要用途是测试,它在生产中的应用有限——新实例化的应用程序及其服务无法与引导应用程序通信,因为服务单例不同。
Angular 中延迟加载有几个解决方案,最全面的是ocLazyLoad .
关于javascript - AngularJS 在引导后添加依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32324526/