Could a personalized "exit page" confirmation be created?

I am looking for a solution that will allow me to pause the execution of my code, display a dialog box, and then resume execution only after a specific button is pressed.

For example, if a user navigates from one page to another on my website, I want a dialog box to appear. If the user confirms the action by clicking a button in the dialog box, then the navigation should continue.

I am aware of the $routeChangeStart event, which provides information about the next route, but it seems to only handle preventing the route change. I am interested in finding a way to delay the route change and trigger it later.

My ideal approach would involve using event.preventDefault() within $routeChangeStart, storing the details of the next route, and then triggering the route change confirmation through user interaction.

Does anyone know how I could reapply a route change? One potential method could involve manipulating the originalPath using the params object and $location, but I am curious if there is a more direct way to achieve this.

Answer №1

It is necessary to utilize string-parsing in this scenario.

If you prefer to handle the confirmation asynchronously, the recommended approach is to prevent the event by default, prompt the user for confirmation, and if granted, set a flag before using $location.url(...) to navigate to the desired page.

app.controller('myCtrl', function ($location, $scope, UserConfirm) {
    $scope.$on('$locationChangeStart', function (evt, next, prev) {
        if (!$scope.exitConfirmed) {
            evt.preventDefault();
            var url = extractUrl(prev, next);
            UserConfirm.confirm('Are you sure you want to leave ?').then(
                function (confirmed) {
                    if (confirmed) {
                        $scope.exitConfirmed = true;
                        $location.url(url);
                    }
                }
            );
        }
    });
    ...
});

The extractUrl() function could be implemented as follows:

function extractUrl(prevAbsUrl, nextAbsUrl) {
    var idx = prevAbsUrl.length - $location.url().length;
    var withNumSign = nextAbsUrl.substring(idx);
    var pureUrl = withNumSign.substring(withNumSign.indexOf('/'));
    return pureUrl;
}

Take a look at this brief demonstration.

Answer №2

Using the $locationChangeStart event, you can access the complete URLs of both your current and future destinations without the need for parsing.

My approach to handling this was as follows:

function confirmLeaving(evt, next, current) {
  if(consideringClosing)  //allow leaving
    return;

  evt.preventDefault();  //Display dialog instead of leaving.

  $('#dialogCancel').modal('show');
  consideringClosing = true;  //It's okay to leave if user tries again after opening dialog.
}   

$scope.$on('$locationChangeStart', confirmLeaving);

Within the modal, there is a "close without saving" button that triggers a $location back to the item list. Since consideringClosing is now true, the confirmLeaving function won't prevent the action. Additionally, the modal contains a cancel button that closes it and resets consideringClosing to false (ensuring the modal will reappear on location change).

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

The Photoswipe default user interface cannot be located

While attempting to incorporate PhotoSwipe into my website, I encountered an uncaught reference error related to The PhotoswipeUI_Default is not defined at the openPhotoSwipe function Below is the code snippet that I have been working on: <!doctyp ...

Is there a way to incorporate a computed value into a table prop while working with Element UI?

In my frontend development, I am utilizing vuejs along with element ui. I am faced with the task of rendering a table that includes dates in unix format. To make these dates more user-friendly, I have incorporated moment.js to convert them into a readable ...

The Problem with AJAX Error Handling Customization

Upon loading my webpage using Code Igniter and PHP, the JSON encoded query is returned successfully with data. I have managed to handle the scenario where no records are found by encoding a response in JSON format. However, I am unsure of how to transmit t ...

My experience with jquery addClass and removeClass functions has not been as smooth as I had hoped

I have a series of tables each separated by div tags. Whenever a user clicks on a letter, I want to display only the relevant div tag contents. This can be achieved using the following jQuery code: $(".expand_button").on("click", function() { $(th ...

Create an input field dynamically by utilizing the append method in jQuery

Concern: As part of an edit page, I am working on appending an input field from a modal window to an existing panel while retaining the format of the rest of the fields. The user is currently able to create and add the new field using the code provided in ...

Implementing logic with multiple columns in JavaScript

Looking for a way to display an array of data in multiple columns using Java Script, like this: 1 2 3 4 5 6 7 8 9 instead of 1 4 7 2 5 8 3 6 9 Any suggestions would be greatly appreciated. Thank you. ...

Displaying iframes in AngularJS using a service

I am currently developing an Angular app and encountering some difficulties with rendering a Soundcloud embed iframe in my HTML. The issue arises when I try to display the tracks stored in the array generated by my getTracks function. Despite successfully ...

The code is functioning properly, however it is returning the following error: Anticipated either

Can you explain why this code is resulting in an unused expression error? <input style={{margin:'25px 50px 0',textAlign:'center'}} type='text' placeholder='add ToDo' onKeyPress={e =>{(e.key ==='En ...

Can the text color be customized to match the brightness level of the background area being covered?

Does anyone know of a plugin or method that can automatically change the color of text or swap predefined images/icons based on the average brightness of its parent element's background? If the background is dark, it should make the text white or swit ...

Is JsonEditor capable of editing JSON Schemas effectively?

For a while now, I have been impressed by the functionality of JSON-editor and have been using it to edit documents based on a specific JSON schema. But why stop there? Many users utilize JSON-Editor to make changes to JSON documents according to the corr ...

Retrieve vuex state in a distinct axios template js file

I have encountered an issue with my Vue project. I am using Vuex to manage the state and making axios requests. To handle the axios requests, I created a separate file with a predefined header setup like this: import axios from 'axios' import st ...

What is the reason behind Express exporting a function instead of an object in the initial stages?

In Node.js, when utilizing express, we start by using const express = require('express') to bring in the express module, which will then yield a function. Afterward, we proceed with const app = express() My inquiry is as follows: What exactly ...

Injecting controllers and classes dynamically using AngularJS

I'm currently working on a dynamic widgets list where each widget is defined by its html, class, controller, and name. Some of these parameters may be empty based on the type of widget. These widgets are then loaded dynamically into <li> element ...

Can data be transferred within a callback to the function it encapsulates?

I am currently working on developing a user login system and I find myself in need of querying the database. Being a beginner in coding, I am grappling with the concept of callbacks and how data can be passed once the callback has been executed. My dilemm ...

When the horizontal scroll is turned off, it also disables the functionality of my mobile-friendly

I came across a helpful post on StackOverflow that suggested using the following code to disable horizontal scrolling: html, body { overflow-x: hidden; } This solution did resolve my issue of horizontal scrolling, but unfortunately it caused problems ...

React Hooks encountering issues with keydown/up events functionality

Currently, I am in the process of implementing arrow-based keyboard controls for a game that I have been developing. In order to stay updated with React, I decided to utilize function components and hooks. To showcase my progress, I have put together a dem ...

Loading Datatables using PHP to send JSON data

I seem to be facing some difficulty in troubleshooting the issue within my code. Currently, I am working on a search script and would like to display the results using Datatables. I have a search form that sends data to my PHP file which then returns a JS ...

Exploring nested static properties within TypeScript class structures

Check out this piece of code: class Hey { static a: string static b: string static c: string static setABC(a: string, b: string, c: string) { this.a = a this.b = b this.c = c return this } } class A { static prop1: Hey static ...

I'm noticing that the value in my array keeps changing, but I'm struggling to pinpoint where the change is coming from

Recently, I've come across an issue where a property within my array collection is changing unexpectedly. Here's a snippet of the code from my controller: $http({ method: 'GET', headers: globalData.httpHeader, params: { orderke ...

JQuery/JS function not functioning as expected

Creating HTML with jQuery to retrieve data from a web API. At the start of my script, I defined a function that checks the selected value of a dropdown and assigns it to a global variable. var $seldom; $(document).ready(function () { function chkdom() ...