Q&A
前提
AngurerJS1.6.4で、モーダル表示中のみ画面全体をクリックした際にクリックした要素を取得するプログラムを作っています。
複数のdirectiveから同じ処理をしたいため、その部分をserviceとして切り出してcontrollerから呼び出したいです。
しかし、Controllerからであれば実行できる$window.addEventListenerが、serviceでは起動せずに困っています。
実現したいこと
- モーダル表示中のみ$window.addEventListenerを登録し、クリックした要素をログで取得する。
- 複数のdirectiveから同じ処理をしたいため、その部分をserviceとして切り出してcontrollerから呼び出したい。
- モーダルが非表示になった場合は、登録した$window.addEventListenerをremoveする。
発生している問題・エラーメッセージ
Controllerからであれば実行できる$window.addEventListenerが、serviceでは起動できない。
該当のソースコード
index.html
1<!doctype html> 2<html ng-app="myApp"> 3 <head> 4 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script> 5 <script src="script.js"></script> 6 </head> 7 <body> 8 <div> 9 <div directive1 ng-show="showTagModalFlag1"></div> 10 <div directive2 ng-show="showTagModalFlag2"></div> 11 <div directive3 ng-show="showTagModalFlag3"></div> 12 </div> 13 </body> 14</html>
directive1.html
1 <div class="tagmodal" ng-init="init()"> 2 <button class="btn-square" ng-click="orFlag = !orFlag "> 3 <span ng-show="orFlag">OR</span> 4 <span ng-show="!orFlag">AND</span> 5 </button> 6 ... 7 </div>
script.js
1 angular.module('myApp', []); 2 angular.module('myApp').controller('myApp' , ['$scope', function($scope){ 3 }]); 4 angular.module('myApp').directive('tagmodal', function(){ 5 return { 6 templateUrl: 'directive1.html', 7 controller: ['$scope', 'events', function($scope, events) { 8 $scope.showTagModalFlag = false; 9 $scope.orFlag = false; 10 $scope.init = function(){ 11 const el = function(e) { 12 //ここはserviceにできる 13 events.getLog(e); 14 } 15 $scope.$watch('showTagModalFlag1', function(newValue, oldValue) { 16 //serviceにしたら、EventListenerが登録できない 17 events.eventController($scope.showTagModalFlag1, el) 18 }; 19 }; 20 }] 21 }; 22 }); 23 angular.module('myApp').service('events', function($window) { 24 this.getLog= function(e){ 25 console.log(e.path); 26 }); 27 this.eventController= function(showTagModalFlag, el){ 28 if (showTagModalFlag){ 29 $window.addEventListener('click', el, false); 30 } else { 31 $window.removeEventListener('click', el); 32 } 33 } 34 });
試したこと
動かない原因ネットで調べようとしましたが、何で調べたらよいかよくわかりませんでした…。