我正在使用Angular 1.6.7。我在我的應用程序中創建了多個模塊。如何將父模塊(myApp)中定義的常量(例如「rootURL」)傳遞給子模塊(childApp)?更具體地說,我需要將「rootURL」的值賦給childApp組件的templateUrl,所以我們不必爲每個模塊的根目錄進行硬編碼。我想我知道如何在控制器中共享變量,但不知道如何在組件的定義內部執行該操作。Angular 1.6和多個模塊:在模塊和組件之間共享全局變量
下面是演示的Plunker。在app.module.js中,我定義了一個常量「config」。我能做些什麼,以便當我爲「child」(components/child.component.js)定義組件時,而不是templateUrl:「components/child.html」時,我可以說類似「config.rootURL + child.html 「?我們不必使用常量。
預先感謝您。
// 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", []);
})();
// components/child.component.js
(function(){
"use strict";
// Define controller
function childController() {
this.$onInit = function() {
var vm = this;
vm.child = {
"firstName": "Jack"
}
};
// end of $onInit()
}
// Define component
var child = {
templateUrl: "components/child.html"
, 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>
<!-- components/child.html -->
Child: {{vm.child.firstName}} {{vm.parent.lastName}}
好,注入常在你的孩子控制器:'函數childController(配置){' –