2016-11-21 1 views
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); 
    } 

    } 
}); 

Fiddle

버튼으로 (구성 요소가 DOM에서 제거됩니다, "구성 요소를 파괴"를 클릭하면 NG-경우) $ onDestroy가 트리거됩니다. $ onDestroy가 click 이벤트 등록을 취소하길 원하지만 아무 일도 일어나지 않습니다.

답변

2

매개 변수와 마찬가지로 함수 참조를 on & off 메서드에 전달해야합니다. 전체 클릭 기능 참조를 전달하지 않아도됩니다.

여기

코드

this.$onInit = function() { 
    listener = function() { 
     console.log('You clicked on the document'); 
    }; 
    $document.on('click', listener); 
} 

this.$onDestroy = function() { 
    console.log('$onDestory triggered'); 
    $document.off('click', listener); 
} 

Demo Fiddle

관련 문제