Issue
Title may be confusing. Please find the code below:
//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");
}
}
};
})
I have window.onbeforeunload
event callback function defined. I have the same directive on two different DOM elements. When onbeforeunload
event is raised, it is executed only once. I thought it would execute twice so that I can capture the element level info. But this is not happening. It is executing only in the context of element "test1". May be I am doing something wrong. Any inputs please..
Solution
window.onbeforeunload
can only take one event handler function, so each time a new one is assigned, the existing one is removed. One way to get around this is to "append" to the function if there's already one defined (also changed to use $window
service for better testability)...
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;
}
}
}
};
});
Answered By - Anthony Chu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.