Angular directives are not triggering window level events as anticipated

This code snippet might be a bit confusing. Take a look at 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 am using a window.onbeforeunload event callback function in this code. The directive 'test' is applied to two different DOM elements. When the onbeforeunload event occurs, it only executes once. I expected it to execute twice so that I could gather information about each element individually. However, it seems to only run in the context of the 'test1' element. If there are any suggestions or insights on what might be causing this behavior, please let me know.

Answer №1

window.onbeforeunload is limited to having only one event handler function at a time, meaning that each new assignment will replace the existing one. To work around this restriction, it is possible to "append" to the function in cases where there is already a defined one (this approach also incorporates the use of the $window service for improved 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;
                }
            }

        }
    };
});

Check out this JsFiddle

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting Jquery to Vanilla Javascript: accessing data attributes

Excuse me, I have a question. I would like to convert my code from jQuery to Vanilla JavaScript, but I am not familiar with the logic of jQuery and JavaScript <a href="#" class="btn btn-info btn-sm btn-edit" data-id="<?= $row ...

Encountering a "DOM Exception 11: InvalidStateError" when attempting to use websocket.send

I encountered the following error message: DOM Invalidate exception 11 This error is coming from the code snippet below, but I'm having trouble identifying the root cause. /*The coding style may appear pseudo-stylish with potential syntax errors*/ ...

How to manage $resource requests from a PHP backend with SLIM framework

I'm facing difficulties trying to connect my AngularJS frontend with a PHP backend. I have referred to the following resources: Routing with AngularJS and Slim PHP Despite trying other similar methods, I've spent several days troubleshooting b ...

Command unitTest controller yields an empty result

I am facing an issue while testing an angular directive. Despite having successfully done it in the past, I seem to have hit a roadblock today. It's probably just a silly mistake. var element, scope, controller; beforeEach(function() { angular.m ...

The loop seems to be disregarding the use of jQuery's .when() function

I've encountered a challenge with a custom loop that needs to perform a specific function before moving on to the next iteration. Below is the code snippet: function customIteration(arr, i) { if (i==arr.length) return; var message = arr[i]; ...

Enable seamless SCSS inclusion in Vue components through automatic importing

My goal is to import a variables.scss file globally in my Vue project. I have set up my vue.config.js file as follows: module.exports = { css: { loaderOptions: { scss: { additionalData: `@import "@/st ...

Contrast the equality of two arrays with objects

I have two different types of data structures var dataA = [ { "Employee Name": "Mr. X", id: "1" }, { "Employee Name": "Mr. Y", id: "2" }, { "Employee Name": "Mr. Z", id: "3" } ]; var dataB = [ { id: "1", " ...

Experiencing problems with lining up several circular items in a row

For my project, I am trying to showcase multiple circular shapes with percentages in a row, but I am encountering some issues. I attempted using a div with display flex, but it doesn't seem to be working as expected. Here is what I have tried so far: ...

Can you walk me through how async/await works?

Can someone provide a detailed explanation of this code? const promiseFactory = () => new Promise(resolve => setTimeout(() => resolve(1), 5000)); If I execute the following: const consumer = async() => { promiseFactory().then(s => con ...

Angular Script Linking

Hello there! I am currently attempting to add an HTML tag to my response message, but for some reason it isn't working as expected. Here is a snippet of my controller code (in case the API indicates that the account doesn't exist - see this scr ...

Guide on utilizing AngularJS Filter service without HTML for Chrome extension development

Currently, I am attempting to utilize the filter service in AngularJS within my Chrome extension. However, I am unsure of how to properly obtain and inject it into my function. At this time, my code looks like: chrome.contextMenus.onClicked.addListener(fu ...

Creating an Array module in Node JS

Adding a prototype to the Array class can be done in native javascript with the following code: var myArray = Array; myArray.prototype.myMethod = function(){} var testArray = new myArray(); testArray.contains(); Now I need to achieve this using a nod ...

Setting Up Custom Dimensions in Google Analytics with Angulartics: A Step-by-Step Guide

Currently, I have integrated Angulartics into my AngularJS application to track certain information to Google Analytics. One of the requirements is to set a Custom Dimension, similar to using the ga('set', 'dimension5', 'custom da ...

"Troubleshooting: Sending null values through Jquery ajax to an MVC controller

The issue: I am facing a challenge with saving events in a calendar through ajax by sending the content to my controller function. Despite my efforts, I constantly see null values being passed to my database. Upon inspecting the Network tools console log ...

Setting the value of an <h1> element using data from an API response - A simple guide

I have been attempting to update the title of a page using data from an API. Here is my HTML: <h1 id='league_name'></h1> This is my JavaScript code: <script> fetch('https://api.example.com') .then(response ...

Change the format of the modelValue to align with the viewValue within an Angular directive

I need to customize the format of a datepicker in a form. The challenge is to display the date in 'dd/mm/yyyy' format for the user, while sending it in ISO format to an API. Below is the directive I am using: app.directive('standardDatepic ...

Error: Phonegap displaying incomplete or corrupted image

Currently, my Android application is being developed with Phonegap. Users have the ability to take photos that are then stored in a mysql database (medium-blob column) using a simple INSERT INTO query without altering the data. These images are then sent s ...

The website encountered an error in loading with the error message "ENOTFOUND" in Cypress

All my cypress tests were running smoothly until one day they all failed to visit the target site. The error message that I received was: cy.visit() failed trying to load: https://mywebsite.com/accounts/login/ We attempted to make an http request to this ...

Can Vue/JavaScript code be transmitted within an object to a different component?

The scenario involves a parent and child Vue components. In this setup, the child component transmits data to the parent component via a simple object emitted using the emit method. Data in the child component: const Steps [ { sequenc ...

There seems to be an issue with the CSV file, possibly indicating an error or the file may not be an SYLYK file when

After developing a node.js script to convert an array object into CSV format using the "objects-to-csv" library from NPM, I encountered an issue when opening the generated CSV file in WPS and Microsoft Office. The warning suggested that there was either an ...