【发布时间】:2015-09-01 06:00:29
【问题描述】:
我想在 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>
script.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");
});
});
script2.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
为什么它不起作用?我该如何解决?
【问题讨论】:
-
为什么你认为这不起作用? plnkr.co/edit/T7B5t9KZTKGpSAfkJxsj?p=preview
-
@lukkea 如果它工作正常,它应该显示
it's running警报框。 -
我怀疑当您通过 requires.add 添加时不会发生 .run (加载脚本时应用程序已经运行);您是否尝试过向 app.main 添加服务并从应用程序调用该服务? (我意识到这可能不适合您的解决方案,但至少它可以让您了解 app.main 是否实际上正确加载以供从应用程序使用。
标签: javascript angularjs dependency-injection bootstrapping