0
앵글 구성 요소가 파손되었을 때 문서 클릭 수신기를 제거하려면 어떻게합니까?앵글 구성 요소에서 클릭 리스너를 등록 해제하는 방법은 무엇입니까?
간체 데모 코드 :
<div ng-app="app">
<div ng-controller="TestingCtrl as vm">
<my-component ng-if="vm.showComponent"></my-component>
<br><br><br>
<button ng-click="vm.setShowState(false)">
Destroy component
</button>
</div>
</div>
Javascipt :
angular.module('app', [])
.controller('TestingCtrl', function TestingCtrl() {
this.showComponent = true;
this.setShowState = function(state) {
this.showComponent = state;
}
})
.component('myComponent', {
bindings: {
name: '@'
},
template: 'myComponent',
controller: function ($document) {
var listener;
this.$onInit = function() {
listener = $document.on('click', function() {
console.log('You clicked on the document');
});
}
this.$onDestroy = function() {
console.log('$onDestory triggered');
$document.off('click', listener);
}
}
});
버튼으로 (구성 요소가 DOM에서 제거됩니다, "구성 요소를 파괴"를 클릭하면 NG-경우) $ onDestroy가 트리거됩니다. $ onDestroy가 click 이벤트 등록을 취소하길 원하지만 아무 일도 일어나지 않습니다.