重新打开并将依赖项添加到已经引导的应用程序 [英] re-open and add dependencies to an already bootstrapped application

查看:20
本文介绍了重新打开并将依赖项添加到已经引导的应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法向已经引导的 angular 模块注入后期依赖?这就是我的意思:

Is there a way to inject a late dependency to an already bootstrapped angular module? Here's what I mean:

假设我有一个站点范围的 angular 应用程序,定义为:

Say that I have a site-wide angular app, defined as:

// in app.js
var App = angular.module("App", []);

并且在每一页中:

<html ng-app="App">

稍后,我将重新打开应用程序以根据当前页面的需要添加逻辑:

Later on, I'm reopening the app to add logic based on the needs of the current page:

// in reports.js
var App = angular.module("App")
App.controller("ReportsController", ['$scope', function($scope) {
  // .. reports controller code
}])

现在,假设这些按需逻辑位之一也需要它们自己的依赖项(例如 ngTouchngAnimatengResource,等等).如何将它们附加到基础应用程序?这似乎不起作用:

Now, say that one of those on-demand bits of logic also requires their own dependencies (like ngTouch, ngAnimate, ngResource, etc). How can I attach them to the base App? This doesn't seem to work:

// in reports.js
var App = angular.module("App", ['ui.event', 'ngResource']); // <-- raise error when App was already bootstrapped

我意识到我可以提前做所有事情,即 -

I realize I can do everything in advance, i.e -

// in app.js
var App = angular.module("App", ['ui.event', 'ngResource', 'ngAnimate', ...]);

或者自己定义每个模块,然后将所有内容注入主应用程序(更多信息请看这里):

Or define every module on its own and then inject everything into the main app (see here for more):

// in reports.js
angular.module("Reports", ['ui.event', 'ngResource'])
.controller("ReportsController", ['$scope', function($scope) {
  // .. reports controller code
}])

// in home.js
angular.module("Home", ['ngAnimate'])
.controller("HomeController", ['$scope', '$http', function($scope, $http){
  // ...
}])

// in app.js, loaded last into the page (different for every page that varies in dependencies)
var App = angular.module("App", ['Reports', 'Home'])

但这需要我每次都使用当前页面的依赖项初始化应用程序.

But this will require I initialize the App everytime with the current page's dependencies.

我更喜欢在每个页面中包含基本的 app.js 并简单地向每个页面引入所需的扩展(reports.jshome.js 等),而不必在每次添加或删除某些内容时修改引导逻辑.

I prefer to include the basic app.js in every page and simply introduce the required extensions to each page (reports.js, home.js, etc), without having to revise the bootstrapping logic everytime I add or remove something.

当应用程序已经启动时,有没有办法引入依赖项?什么被认为是这样做的惯用方式(或方式)?我倾向于后一种解决方案,但想看看我描述的方式是否也可以完成.谢谢.

Is there a way to introduce dependencies when the App is already bootstrapped? What is considered the idiomatic way (or ways) to do this? I'm leaning towards the latter solution, but wanted to see if the way I described could also be done. thanks.

推荐答案

我是这样解决的:

再次引用该应用:

var app = angular.module('app');

然后将您的新需求推送到需求数组:

then push your new requirements to the requirements array:

app.requires.push('newDependency');

这篇关于重新打开并将依赖项添加到已经引导的应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆