2016-07-21 4 views
1

상태를 변경하고 dom 요소를 변경 한 후에도 내 지시문의 코드가 멈추지 않는 이유를 이해하는 데 어려움을 겪고 있습니다. 지시문을 제한하고 있습니다. 더 이상 사용 가능한보기에 없습니다. 아래 코드 예제에서 홈 페이지에서 시작하면 document.addEventListener 함수가 마우스를 눌렀을 때 실행되지 않습니다. 이는 예상했던 것입니다. 그런 다음 "test"클래스가있는 div가있는 our_purpose 상태가 발생하면 예상대로 클릭 이벤트가 발생합니다. 그러나 홈 상태로 돌아 가면 이벤트 수신기가 계속 유지됩니다.각도를 상태 변경시 지시문 코드 실행을 멈추는 방법

내 테스트 지시문 내에있는 모든 코드를 제거하고 더 이상 작동하지 않게하려면 어떻게해야합니까? 지시문에서 모든 것을 다시 시작하여 해당 지시문이있을 때까지 더 이상 존재하지 않게하는 방법이 있습니까? 전망?

이것은 실제 작동 코드의 단순화 된 버전입니다. 그러나 다른 상태에있을 때 문제를 일으키는 많은 기능이 실제 지시문에 있습니다.

var app = angular.module('app', ['ui.router']); 

app.directive("test", function() { 
    return { 
     scope: true, 
     transclude: false, 
     controller: 'OurPurposeCtrl', 
     restrict:"C", 
     link:function(scope, elem, attr) { 
      function testThis() { 
       console.log("still running the directive"); 
      } 
      function init() { 
       document.addEventListener('mousedown', testThis, false    ); 
      } 
      init(); 

     } 
    } 
}); 

app.config(['$stateProvider','$urlRouterProvider', 
    function($stateProvider, $urlRouterProvider) { 
     $stateProvider 
      .state('home', { 
       url: '/', 
       controller: 'landing', 
       templateUrl: 'views/landing.html' 
      }) 

      .state('our_purpose', { 
       controller: 'OurPurposeCtrl', 
       url: '/our-purpose', 
       templateUrl: 'views/our-purpose.html' 

      }) 
    } 
]); 
+0

당신은 제거되지 않은 이벤트를 사용하여 범위의 이벤트를 파괴하지 않고 파괴 결코 극복 청취자 그리고 자동으로 발생하지 않습니다 - 여기 좀 봐 : http://stackoverflow.com/a/27016855/5131537 – JanisP

+0

예. 정확히 그것. – Starfs

답변

2

당신은 문서로 리스너를 부착하고 그렇게 청취자 중 하나

제거 이벤트 리스너에서 scope.$on('$destroy', function)

app.directive("test", function($document) { 
    return { 
     scope: true, 
     transclude: false, 
     controller: 'OurPurposeCtrl', 
     restrict:"C", 
     link:function(scope, elem, attr) { 
      function testThis() { 
       console.log("still running the directive"); 
      } 
      function init() { 
       $document.bind('mousedown', testThis); 
      } 
      init(); 

      scope.$on('$destroy', function(){ 
       $document.unbind('mousedown', testThis); 
       console.log('Mousedown listener should be gone'); 
      }); 

     } 
    } 
}); 
+0

네, 당신은 정확합니다. 내 특정 인스턴스에 대한 보조 노트로서 나는 이것을 파괴 기능에 넣어야했다. document.removeEvenLtistener ('mousedown', testThis); 나는 이것이 덜 각진 접근법이라고 생각 하나? – Starfs

+0

오른쪽, jQuery 메서드의 하위 집합이지만 [jQuery] 종속성이없는 [angular.element] (https://docs.angularjs.org/api/ng/function/angular.element)를 사용했습니다. 쓰기가 더 짧다. – charlietfl

관련 문제