angular指令中的窗口级事件没有按预期执行
Window level events in angular directives are not executing as expected
标题可能令人困惑。请查看下面的代码:
//html
<div id="test1" test></div>
<div id="test2" test></div>
//module
var myApp = angular.module('app', []);
myApp.directive('test', function () {
return {
link: function (scope,el,attr) {
window.onbeforeunload = function () {
console.log("test1");
}
}
};
})
我已经定义了window.onbeforeunload
事件回调函数。我对两个不同的DOM元素有相同的指令。当引发onbeforeunload
事件时,它只执行一次。我认为它会执行两次,这样我就可以捕获元素级别的信息。但这并没有发生。它只在元素"test1"上下文中执行。也许我做错了什么。
window.onbeforeunload
只能接受一个事件处理函数,因此每次分配一个新的事件处理函数时,都会删除现有的事件处理函数。解决这个问题的一种方法是"附加"到已经定义的函数(也改为使用$window
服务以获得更好的可测试性)…
myApp.directive('test', function ($window) {
return {
link: function (scope, el, attr) {
appendOnbeforeunload(function () {
console.log(el.attr('id'));
});
function appendOnbeforeunload(fn) {
var currentFn = $window.onbeforeunload;
if (angular.isFunction(currentFn)) {
$window.onbeforeunload = function () {
currentFn();
fn();
};
} else {
$window.onbeforeunload = fn;
}
}
}
};
});
JsFiddle
相关文章:
- 使用react js在跨域上执行事件javascript
- 如何使用cURL或其他方式在点击时执行事件
- javascript执行事件顺序
- While Scrolling:如果scrollTop()等于或达到一个值,则执行事件
- 如何使用gulp-jslint-simple成功执行事件
- 如果初始事件返回 false,则停止执行事件侦听器
- 我怎么能等待在javascript中执行事件
- 使用 AJAX 在 jQuery 和 C# 之间传递变量和执行事件
- 执行 C# 事件处理程序,然后执行该 js 函数
- Vue.js 在组件渲染后执行事件触发器
- 在事件的自然行为之前执行事件
- javascript更改类没有't执行事件
- 如何按顺序执行事件函数
- 在worker上执行事件对象.Onmessage从不包含任何有趣的数据之外的东西
- 选项更改,执行事件javascript
- 使用node.js在进程终止时执行事件
- 从此特定父类查找兄弟类以执行事件
- 使用jquery创建弹出窗口并执行事件
- Javascript执行事件点击
- 单击除一个元素之外的所有内容时执行事件