使用在子模块内部的父模块上定义的常量's配置

use constant defined on parent module inside child module's configuration

本文关键字:模块 常量 配置 定义 内部      更新时间:2023-09-26

我有main角度模块,它知道服务器url,我这样设置它:

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

我还有editor模块,main模块依赖于它。Editor模块知道与之对话的服务器上的控制器名称(editor),但不知道服务器URL,所以我想使用editor模块中的serverUrl常量来定义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/")
}]);

您可以尝试类似的

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中的第三个模块,或者在主模块内部配置所有模块。

注意:内部角度没有模块,所以无论在哪里声明这个常数