###前提・実現したいこと
AngularJSを使って、システムを作ろうとしています。
共通のモジュールを作って、そこから共通の表示ができるようにしたいと考えています。
イメージとしては、例えば、モーダルダイアログを共通化したいと考えています。
モーダルダイアログのコンポーネントを作っておいて、どこからでも共通のモーダルダイアログが呼び出せるようにできないか、と考えています。
htmlに<modal></modal>
と書いておけば、どこからでもmodalを操作できるようになったりしないかな?と思い、質問させていただきました。
実装イメージ
js
1var common = angular.module( "common", [] ); 2common.component( "modal", { 3 template: "<div class="modal" ng-bind="$ctrl.message" ng-show="$ctrl.isShowing"></div>", 4 controller: function() { 5 var that = this; 6 this.message = ""; 7 this.show = function( message ) { 8 that.message = message; 9 that.isShowing = true; 10 } 11 } 12} ); 13 14var app = angular.module( "myApp", [ "common" ] ); 15app.component( "parent", { 16 template: "<modal></modal>" + 17 "<button ng-click=\"$ctrl.onClick()\">Alert</button>"; 18 controller: function() { 19 var that = this; 20 this.onClick = function() { 21 // なんらかの手段で alert.show( "Hello World!" ); したい・・・! 22 } 23 } 24} );
知りたいこと
このとき、parent
コンポーネントはどのようにしてalert.show()
すればよいでしょうか?
そもそも、このような実装がAngularJSとしてふさわしくないものなのでしょうか?
ふさわしくない場合、どのようにするのが正解なのでしょうか?
###試したこと
$scope
などを利用し、親から子へ入れ物を受け渡しておき、子が入れ物に、自身を入れることで、とりあえず親が子を参照できるようにはなりましたが、あまりきれいな実装とは思えず、正しい方法が知りたいのです。
js
1alertController = function( $scope ) { 2 $scope.child.alert = this; 3 this.show = function() { 4 // 省略 5 } 6}; 7 8parentController = function( $scope ) { 9 $scope.child = {}; 10 this.onClick = function() { 11 $scope.child.alert.show( "Hello World!" ); 12 } 13}
###補足情報(言語/FW/ツール等のバージョンなど)
- AngularJS v1.6.4を利用しています。
回答1件
あなたの回答
tips
プレビュー