2

Angular 1.6.7 を使用しています。アプリで複数のモジュールを作成しました。親モジュール (myApp) で定義された定数 (「rootURL」など) を子モジュール (childApp) に渡すにはどうすればよいですか? 具体的には、「rootURL」の値を childApp のコンポーネントの templateUrl に割り当てる必要があるため、すべてのモジュールのルート ディレクトリをハードコーディングする必要はありません。コントローラー内で変数を共有する方法は知っていると思いますが、コンポーネントの定義内でそれを行う方法がわかりません。

これがデモ用のプランカーです。app.module.js で、定数の "config" を定義しました。「子」(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}}

4

2 に答える 2