在子模块的配置中使用父模块上定义的常量

时间:2015-03-22 15:44:05

标签: javascript angularjs

我有main角度模块,它知道服务器网址,我设置如下:

angular.module('main', ["editor"]).constant("main.serverUrl", "http://serverurlhere.com")

我还有editor模块所依赖的main模块。 Editor模块知道它所访问的服务器上的控制器名称(editor),但不知道serverUrl,所以我想在serverUrl内使用editor常量用于定义editor.serverUrl常量的模块:

angular.module('editor').constant("editor.serverUrl", main.serverUrl + "/editor")

我该怎么做?

更新

var m = angular.module("main", ["editor", "mainModuleProviders"]);
var mProviders = angular.module("mainModuleProviders", []);
mProviders.constant("serverUrl", "http://someserverurl.com");

var e = angular.module("editor", ["mainModuleProviders"]);
e.config(["serverUrl", "$provide", function(serverUrl, $provide){
  $provide.value("editor.serverUrl", serverUrl + "/editor/")
}]);

1 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情

var e = angular.module("editor", [])
               .constant("editor.url", "/editor");

var m = angular.module("main", ["editor"]);
    m.constant("serverUrl", "http://someserverurl.com");


m.config(["editor.url","serverUrl", "$provide", function(eu,se,$provide){
  $provide.constant("editor.serverUrl",se+eu);
}]);    

var e = angular.module("editor", [])
  .constant("editor.url", "/editor");

var m = angular.module("main", ["editor"]);
m.constant("serverUrl", "http://someserverurl.com");


m.config(["editor.url", "serverUrl", "$provide",
  function(eu, se, $provide) {
    $provide.constant("editor.serverUrl", se + eu);
  }
]);

e.controller('ctrl', ["$scope", "serverUrl", "editor.url", "editor.serverUrl",
  function($scope, su, eu, seu) {
    $scope.serverUrl = su;
    $scope.editorUrl = eu;
    $scope.editorServerUrl = seu;
  }
])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="main" ng-controller="ctrl">
  <div>serverUrl = {{serverUrl}}</div>
  <div>editorUrl = {{editorUrl}}</div>
  <div>editorServerUrl = {{editorServerUrl}}</div>
</div>

<强>更新
在AngularJS中使用依赖注入,因此当您在模块中添加依赖项时,必须在此模块运行之前加载它 在您的第一个变体中:您尝试在编辑器模块中使用依赖于编辑器模块的主模块 要解决此问题,您可以使用第二个变量 mainModuleProviders 中的第三个模块,或者配置所有内部主模块。

注意 :里面的角度没有模块,所以无论在哪里声明这个常量