[Angularjs]如何动态添加服务到角度模块?
Posted
技术标签:
【中文标题】[Angularjs]如何动态添加服务到角度模块?【英文标题】:[Angularjs]How to dynamic add a service to angular module? 【发布时间】:2018-05-30 15:40:33 【问题描述】:我想向我的 Angularjs 模块动态添加一些服务。不知道有什么方法可以做到吗?
// Senarios config for dev
let scenarioConfig1 = require(`./$env/scenarios_config_files/scenario1.config`);
let scenarioConfig2 = require(`./$env/scenarios_config_files/scenario2.config`);
let scenarioConfig3 = require(`./$env/scenarios_config_files/scenario3.config`);
let scenarioConfig4 = require(`./$env/scenarios_config_files/scenario4.config`);
let scenarioConfig5 = require(`./$env/scenarios_config_files/scenario5.config`);
let scenarioConfig6 = require(`./$env/scenarios_config_files/scenario6.config`);
//I wonder if there is any way, I can add these 6 service dynamically to my Angularjs
//Module instead adding them one by one
module.exports = angular.module('myApp', [])
//scenarios config service for dev and prod
.service('scenarioConfig1', [
scenarioConfig1])
.service('scenarioConfig2', [
scenarioConfig2])
.service('scenarioConfig3', [
scenarioConfig3])
.service('scenarioConfig4', [
scenarioConfig4])
.service('scenarioConfig5', [
scenarioConfig5])
.service('scenarioConfig6', [
scenarioConfig6]);
【问题讨论】:
【参考方案1】:可以这样做:
let services = [
'scenario1',
'scenario2',
'scenario3'
].map(s =>
return
name: s.replace(/(\d+$)/, 'Config$1'),
func: require(`./$env/scenarios_config_files/$s.config`)
);
let app = angular.module('myApp', []);
services.forEach(o => app.service(o.name, [o.name, o.func]));
module.exports = app;
【讨论】:
以上是关于[Angularjs]如何动态添加服务到角度模块?的主要内容,如果未能解决你的问题,请参考以下文章
AngularJS 创建另一个模块并将其作为依赖项添加到 first
如何在jquery datepicker中向html属性添加角度标签