【发布时间】:2017-09-19 18:39:58
【问题描述】:
如何将常量的值从一个模块传递到另一个模块?先感谢您。这是Plunker 演示。常量“config”在 app.module.js 中定义,我希望能够将它传递给 child.module.js 以定义常量“childConfig”。现在控制台说“配置未定义”。
非常感谢您。
// app.module.js
(function(){
"use strict";
var myApp = angular
.module("myApp", ["child"]);
myApp.constant("config", {
rootURL: "components/"
, version: "myApp1.0.0"
})
})();
// app.component.js
(function(){
"use strict";
// Define controller
function mainController(){
this.$onInit = function() {
var mainVM = this;
mainVM.parent = {
"lastName": "Smith"
, "firstName": "Jordan"
};
};
}
// Define component
var mainComponent = {
controller: mainController
, controllerAs: "mainVM"
};
// Register controller and component
angular.module("myApp")
.controller("mainController", mainController)
.component("mainComponent", mainComponent);
})();
//components/child.module.js
(function(){
"use strict";
var child = angular.module("child", []);
child.constant("childConfig", config);
})();
//components/child.component.js
(function(){
"use strict";
// Define controller
function childController(config) {
this.$onInit = function() {
var vm = this;
vm.getTemplateUrl = function(){
return config.rootURL + 'child.html';
}
vm.rootURL = config.rootURL;
vm.version = config.version;
vm.child = {
"firstName": "Jack"
}
};
// end of $onInit()
}
// Define component
var child = {
//templateUrl: vm.getTemplateUrl + "child.html"
//templateUrl: "components/child.html"
template: "<ng-include src='vm.getTemplateUrl()'/>"
, controller: childController
, controllerAs: "vm"
, bindings: {
parent: "<"
}
};
// Register controller and component
angular.module("child")
.controller("childController", childController)
.component("child", child);
})();
<!DOCTYPE html>
<html>
<head>
<script src="//code.angularjs.org/snapshot/angular.js"></script>
<link rel="stylesheet" href="style.css">
<script src="app.module.js"></script>
<script src="app.component.js"></script>
<script src="components/child.module.js"></script>
<script src="components/child.component.js"></script>
</head>
<body ng-app="myApp" ng-controller="mainController as mainVM">
Parent: {{mainVM.parent.firstName}} {{mainVM.parent.lastName}}<br>
<child parent="mainVM.parent"></child>
</body>
</html>
【问题讨论】:
-
两次定义同一个常量有什么意义?只需在需要的地方注入配置常量。
-
不,我没有定义相同的常量两次。我正在开发的实际应用程序要大得多,并且有很多级别。我需要在每个子常量的定义中使用父常量,以便它们可以在自己的控制器中使用。当我更新 rootURL 时,所有子 URL 都将被更改。我已经更新了 Plunker 来证明这一点。
-
不要为您的子配置定义常量。定义一个服务,您可以在其中注入根常量,并返回一个对象,其中包含其值取决于注入的常量的字段。
-
这是有道理的。谢谢。
标签: angularjs angular1.6