使用Angular JS将常量注入其他模块配置 [英] Inject constant to other modules config using Angular JS

查看:63
本文介绍了使用Angular JS将常量注入其他模块配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在整个应用程序中共享一些变量,例如基本路径. 这些变量需要在模块配置期间访问. 我的意见是,我可以为此使用常量或提供程序.

I would like to share some variables like base paths throughout my application. These variables needs to be accessible during module configuration. My opinion was, that I can use a constant or provider for that.

我有几个模块,每个模块都有自己的路由配置.在这些路由配置中,例如,我要访问一些设置.

I've got several modules and each one has it's own routing configuration. In these routing configurations, I want to access some settings for example.

这适用于app-module-configuration,但不适用于其他模块配置(对于其他模块上的控制器而言),我总是收到未知提供者:来自myApp.orders的信息".

This is working for the app-module-configuration but not for other module-configurations (for controllers on other modules it does), I always get "Unknown provider: info from myApp.orders".

var myApp = angular.module('myApp', ['myApp.orders']);

myApp.constant('info', {
  version : '1.0'
});

myApp.config(function(info) {
  console.log('app config: ' + info.version);
});

myApp.controller('MyController', function (info) {
  console.log('controller: ' + info.version);
});

var orders = angular.module('myApp.orders', []);

// Remove comments to see it fail.

//orders.config(function(info) {
//  console.log('orders config: ' + info.version);
//});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

  <div ng-app="myApp" class="container" ng-controller="MyController">        
  </div>

我想我只是错过了一些细节,您有想法吗?

I guess I have just missed out a little detail, do you have an idea?

推荐答案

您的info常量在myApp模块中定义.如果我正确理解了您的问题,则希望在其他模块(例如myApp.orders模块)中使用常量.如果是这样,那么您需要将myApp注入myApp.orders中,但是看起来您想做相反的事情.一种解决方案是将常量解耦到独立模块中,并在需要时将其作为依赖项注入.

Your info constant is defined in your myApp module. If I understand your question correctly, you'd like to use the constants in other modules (e.g. myApp.orders module). If so, then you need to inject myApp into myApp.orders, but it looks like you want to do the reverse. One solution is to decouple the constants into a standalone module, and inject it as a dependency where needed.

angular.module('constants', []) 
  .constant(...);

angular.module('myApp', ['constants', 'myApp.orders'])
  ...

angular.module('myApp.orders', ['constants'])
  ...

这篇关于使用Angular JS将常量注入其他模块配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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