【问题标题】:AngularJS add dependencies after bootstrappedAngularJS在引导后添加依赖项
【发布时间】: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


【解决方案1】:

moduleName.requires 未记录,难以理解,used only by Angular injector。反过来,在引导过程中调用注入器(通过ng-appangular.bootstrap)或使用angular.injector 创建新的注入器。

一旦应用启动并且配置/运行阶段结束,就无法调用新的配置/运行块。同样关注moduleName.directivemoduleName.controller 和其他模块方法,它们都应该在应用程序启动之前被调用。因此,它们不适合异步定义模块。

新定义的运行块可以被称为by creating an injector explicitly(这意味着创建了一个新的应用实例):

var newApp = angular.injector(['app.main']);

它的主要用途是测试,它在生产中的应用程序有限 - 新实例化的应用程序及其服务无法与引导应用程序通信,因为服务单例不同。

Angular中懒加载的解决方案有几种,最全面的就是ocLazyLoad

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2015-01-10
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多