gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:31:42 24 4
gpt4 key购买 nike

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

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

我还有 editor 模块,main 模块依赖于该模块。 Editor 模块知道与之通信的服务器上的 Controller 名称 (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/")
}]);

最佳答案

你可以试试这样的东西

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 中使用依赖注入(inject),所以当你在你的模块中添加依赖时,它必须在这个模块运行之前加载。
在您的第一个变体中:您尝试使用依赖于编辑器模块内的编辑器模块的主模块。
为了解决这个问题,您可以使用第二个变体 mainModuleProviders 中的第三个模块,或者在主模块中配置所有内容。

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

关于javascript - 在子模块的配置中使用在父模块上定义的常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29196345/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com