Different methods of managing exit from a template in AngularJS?

Currently, I am working on incorporating a feature into my Angular module that will prompt an event to save any changes made on the page. There are multiple ways in which a user can navigate away from the page:

  1. Clicking on a link that directs to a new template.
  2. Using the back button in the browser.
  3. Closing the browser tab or window.

For handling scenario #1, I have utilized the following code snippet:

.directive('confirmOnExit', function() {
    return {
        link: function($scope, elem, attrs) {
            window.onbeforeunload = function(){
                    return "If you leave this page, you will exit the practice session. You will be able to view your score report for the completed session but will have to start a new one if you want to continue practicing.";
            }
            $scope.$on('$locationChangeStart', function(event, next, current) {
                    if($scope.$dirty & confirm("Are you sure you want to leave this practice session?")) {
                        console.log("Will end session!");
                        end_session();
                    }
            });
        }
    };
});

However, it seems like when encountering situations #2 and #3, although the popup dialog appears, the end_session() function is not being triggered as expected.

I am open to suggestions and insights on how to address the issue of dealing with the back button and closing the tab/window effectively.

Answer №1

It seems like there may be a race condition occurring. The end_session() function might not be triggering before the page is fully unloaded by the browser. Without seeing more of your code, it's hard to provide specific assistance since I am unfamiliar with what exactly end_session() does.

One potential solution could be to capture the locationChangeStart event and postpone it until all other tasks related to unloading are completed.

It's worth noting that directly referencing the window object in Angular is considered an anti-pattern. You can find more information on this topic here: https://docs.angularjs.org/api/ng/service/$window

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

Having trouble accessing the next page when clicking on the icon

I'm attempting to switch to a new page when clicking on the icon, and my component code looks like this: getTabDetails() { switch (this.tabContent) { case 'Shipment content': { this.router.navigateByUrl('/ProjectShi ...

Incorporating an HTML image into a div or table using jQuery

I am a beginner in using JQuery within Visual Studio 2013. My question is how to insert an img tag into a table or div using JQuery? For example, I have a div and I would like to generate an image dynamically using JQuery. Or, I have a dynamically create ...

Tips for displaying multiple results from a MySQL query in a single .ejs file using Node.js and Express

Currently diving into Node.js and working on a web application, I am faced with the challenge of rendering twice in the same .ejs file. Consider the scenario presented in the following .ejs file: <table> <% rows.forEach(function(ind){ %> /* m ...

Choosing image identifiers dynamically upon click

Greetings! I have a setup where images are pulled from a database and displayed in a div. When any image is clicked, a modal showing product details pops up. To make the modal work, I am using JavaScript to get the src of the clicked image and then displa ...

Ways to pass the ng-repeat index from one ng-repeat to another

I am working with an array named "Menu" var Menu = [ "url" : "#", "type" : "F", "id" : "F00001", "name" : "CUST", "child" : [ { "type" : "P", "id" : "C00001", "name" : "CUST INFO" ...

Dealing with a situation where different functions need to be called based on a condition while using unique button names. This is

<button type="button" class="btn btn-primary ms-4" (click)="update()">Save</button> <button type="button" class="btn btn-primary ms-4" (click)="create()">Add</button> B ...

Passing a query variable to an input field through a PHP function

I have developed an autocomplete PHP function that connects to a MySQL database to fetch data based on user input: The PHP file is named search.php and contains the following code: if ( !isset($_REQUEST['term']) ) exit; $dblink = mysql_con ...

Switch out the picture by using JavaScript

I am a beginner in web development and I have a project where I need to replace an existing image on a webpage with one that the user selects from their own computer. The catch is, this needs to be done offline without uploading anything to a server. I a ...

Error: The module 'https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js' is missing the required export 'default'

I'm currently in the process of setting up and testing Google authentication for a web application that I'm developing. Unfortunately, I've encountered several issues with getting the JavaScript functions to work properly, and I am uncertain ...

Error on node: The type of error encountered is TypeError. It appears to be related to req.query.acct_stmt_id not being

I encountered a puzzling issue where a particular route works flawlessly with an input array of size 10, but throws the error TypeError: req.query.acct_stmt_id.map is not a function when the input array size increases to 100. To run node, I am utilizing - ...

An error will be thrown if you try to pass an array attribute of an object as a prop to a React component

I'm trying to grasp why passing an array attribute of a data object into a Component as a prop is causing issues. Is this due to my understanding of how React functions, or are there potential pitfalls in this scenario? Any insight would be greatly ap ...

What is the best way to determine if my controller was invoked while conducting unit tests using sinon?

Just starting out with Unit Testing in Angular and feeling a bit overwhelmed with the concepts of spies, stubs, and mocks. I'm struggling with the basics: Is my controller correctly receiving the services passed to the constructor? Is the method ini ...

Top eCommerce frameworks optimized for Web2 and SaaS integration

Are there any payment and eCommerce frameworks that can seamlessly integrate with a REST-based application right out of the box? My server is Java-based, but I've found limited options in this area. I'm open to wrapping my interface with another ...

The URL may change, but Angular remains on the same page without navigating

I am encountering an issue with 2 links in my application. The first time I click on any one of them, it navigates to the corresponding page without any problem. However, when I click on the second link after that, the URL changes but the navigation does n ...

Troubleshooting: ngModel in Angular 2 Component does not properly update the parent model

I have been attempting to develop a wrapper component for input elements like checkboxes, but I am facing an issue where the parent variable (inputValue) is not updating even though it has been defined as an ngModel. The code snippet for my component look ...

Submitting a Yii 2 form automatically when it loads

Pjax::begin(); $form = ActiveForm::begin(); echo $form->field($model, 'testdata', [ 'inputOptions' => [ 'class' => 'form-control input-xsmall input-inline' ], ...

What are the best practices for storing an array of objects in MongoDB with Mongoose?

For my project, I needed to store data in a mongoDB document as an array of objects using Javascript, Node JS, Express framework, and Mongoose library. After researching online, I found two different methods to achieve this: Creating another sub-schema ...

React Component not retaining its value

I am currently facing an issue with a React component where I need to read a file from an Upload and pass the contents onto a child component for display. Although I can successfully read the file contents using FileReader and see the results in the cons ...

Retrieving information from various datasets through inquiry

First Model const mongoose = require("mongoose"); const finalApprovalSchema = mongoose.Schema({ formId: String, designApproval: String, rejectionReason: String, date: { type: Date, default: Date.now, }, }); const FinalApproval ...

Spinning picture when mouse is clicked

Currently experimenting with the code found at Rotating an element based on cursor position in a separate element and http://jsfiddle.net/JqBZb/ I have rewritten it in its entirety, accessible at the link below, but unfortunately, it's not functionin ...