手动 bootstrap angular 应用创建异步应用初始化

Manually bootstrap angular app to create async app initialization

我正在尝试手动 bootstrap 我的 angular 应用程序,以便异步加载我的应用程序所依赖的一些数据。看到这个 article

问题是无论我尝试什么,我都无法使用 angular.injector 访问工厂实例。看到这个 plunker

问题是我 运行 代码是这样的:

var Injector = angular.injector(["MyAPP", "ng"]);
var initService = Injector.get("MyService");

我刚收到未知的提供商错误。

有人可以帮助我使这个 plunker 工作,或者为我指出创建 angular 应用程序初始化服务的更好方法。谢谢,

已编辑:已更新以反映我们在评论线程中的讨论。

要设置 initApp() 函数以使用 Promise 异步初始化任何所需的应用程序级服务,包括工厂(如原始 plunker 中所定义),您只需 return 一个承诺将在初始注入完成时解决;完成后,将您的 bootstrapApplication() 方法调用到页面上的 bootstrap Angular。

function initApp() {
  return new Promise(function(resolve, reject) {
        var Injector = angular.injector(["ng","plunker"]);
        Injector.invoke(['factoryTwo', function(factoryTwo) { 
          console.log(factoryTwo.test);
          resolve();
        }]);
  });
}


function bootstrapApplication() {
  angular.element(document).ready(function() {
      angular.bootstrap(document, ["plunker"]);
  });
}  

initApp().then(bootstrapApplication);

这里有一个 link 到上面代码片段工作的分叉插件:http://plnkr.co/edit/764AqLZf6rQHwPZ1RAZc?p=preview

您必须 bootstrap 加载 ajax 内容才能插入页面

您需要在 HTML 字符串上调用 $compile,然后再将其插入 DOM,以便 angular 有机会执行绑定。

在你的 fiddle 中,它看起来像这样。

$("#dynamicContent").html(
  $compile(
    "<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
  )(scope)
);

显然,$compile 必须注入到您的控制器中才能正常工作。

阅读 $compile documentation 中的更多内容。