Javascript 如何在更改状态时停止指令代码的运行
我很难理解为什么我的指令中的代码即使在我更改了状态之后也不会停止运行,并且我限制指令的dom元素不再在可用视图中。在下面的代码示例中,如果我从主页开始,document.addEventListener函数将不会在鼠标按下时运行,这是我所期望的。然后,当我得到我们的目的状态时,带有“test”类的div驻留在该状态中,事件按预期在单击时触发。但是,当我导航回主状态时,事件侦听器仍然存在 我如何使我的测试指令中的所有代码都可以删除,不再工作。。。是否有一种方法可以重新启动指令中的所有内容,使其在您进入该视图之前不再存在 这是我的工作代码的简化版本,但是real指令中有很多功能,当您处于另一个状态时会导致问题Javascript 如何在更改状态时停止指令代码的运行,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我很难理解为什么我的指令中的代码即使在我更改了状态之后也不会停止运行,并且我限制指令的dom元素不再在可用视图中。在下面的代码示例中,如果我从主页开始,document.addEventListener函数将不会在鼠标按下时运行,这是我所期望的。然后,当我得到我们的目的状态时,带有“test”类的div驻留在该状态中,事件按预期在单击时触发。但是,当我导航回主状态时,事件侦听器仍然存在 我如何使我的测试指令中的所有代码都可以删除,不再工作。。。是否有一种方法可以重新启动指令中的所有内容,使其在您
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'
})
}
]);
您正在将侦听器附加到文档,它永远不会被破坏,所以侦听器也不会被破坏 使用
scope.$on('$destroy',function)
您没有删除事件侦听器,并且这不会自动发生-请看这里:是的,您是正确的,先生。作为我特定实例的旁注,我必须将其放入destroy函数中。document.removeEventListener('mousedown',testThis);我猜这是一种角度较小的方法?对,我使用了jQuery方法的子集,但没有jQuery依赖性。简写
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');
});
}
}
});