[Angularjs]如何动态添加角度模块的服务?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Angularjs]如何动态添加角度模块的服务?相关的知识,希望对你有一定的参考价值。
我想动态地向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]);
答案
可以这样做:
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]如何动态添加角度模块的服务?的主要内容,如果未能解决你的问题,请参考以下文章
如何在您的 Ionic / AngularJs 应用程序中包含和使用节点模块?