When using Angularjs and UIRouter, calling event.preventDefault() will prevent the default browser behavior and

A custom JavaScript prompt is triggered when a user clicks the back button on their browser by monitoring the $stateChangeStart event. Let's explore this scenario:

Imagine users moving through pages 1, 2, and finally reaching page 3. Upon trying to go back from page 3 using the back button, they encounter a confirmation box. If the user opts to click 'Cancel', event.preventDefault() is invoked, keeping them on the current page. However, if they proceed to click 'OK' upon attempting to go back again, they are taken all the way back to page 1. The whereabouts of page 2 seem baffling. Does event.preventDefault() erase the last history? How can one ensure that the browser does not skip over the preceding page?

$rootScope.$on('$stateChangeStart',
    function (event, toState, toParams, fromState, fromParams) {
        var retVal = confirm("You have unsaved changes. If you leave the page, these changes will be lost.");
        if (retVal == false) {
            // User has chosen to remain on the current page
            event.preventDefault();         
        }
    });

Answer №1

To maintain a history without allowing users to click the Back button, you need to monitor the $locationChangeStart event instead of the $stateChangeStart.

The reason for this is that $stateChangeStart is triggered after the transition has already occurred and the browser history has been updated.

Here's how you should implement it:

$rootScope.$on('$locationChangeStart', function(event, next) {
    var confirmation = confirm("You have unsaved changes. If you leave the page, these changes will be lost.");
    if (confirmation == false) {
        // The user wants to prevent navigating back
        event.preventDefault();         
    }
});

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

Utilizing Node.js and Express.js to Parse HTML Form Inputs

Having trouble extracting input from an HTML form and utilizing it in Node.js. Here is the HTML form being used: <form action="/myform" method="POST"> <input type="text" name="mytext" required / ...

Newbie in JavaScript - reinitiating my for loop journey

After running an animation in 4 steps, I want it to restart once all the steps are completed. var aSteps = [ { "x": "800", "y": "0" }, { "x": "800", "y": "500" }, { "x": "0", "y": "500" ...

Tips for extracting title and image from someone else's blog posts to share on your own website

Currently, I am in the process of creating a website where I can showcase my personally curated content. I have been struggling to figure out how to seamlessly integrate this content into my site without relying on an API. My initial idea was to manually ...

The error message "AngularJS [$injector:unpr] Unknown provider" indicates a

I need help with injecting a service into my controller. I encountered the following error: Error: [$injector:unpr] Unknown provider: employeeServiceProvider <- employeeService http://errors.angularjs.org/1.3.0-beta.17/$injector/unpr?p0=employeeService ...

Encountering an issue: Unable to load resources - Server returned a status code of 500

Struggling with implementing ajax code in my app development. I've encountered an issue where the ajax code that works fine in the video tutorials I'm following doesn't seem to work for me. It's really frustrating! Here is a snippet of ...

Using `on('click') in JQuery has a one-time effect

Although there are many questions similar to this one, I am still having trouble figuring it out. <div class="message"></div> <button id="getMessage">Get Quote</button> $.getJSON("http://quotesondesign.com/wp-json/posts?filter[or ...

The data within an isolated scope is failing to appear in the template of the directive

I am currently working on a custom Angular directive that is designed to showcase pagination throughout my application. Despite using an isolated scope to pass the parameter totalNoOfRecords, I am facing issues with it not being displayed. Any assistance ...

What is the reason for recursion not producing a new object as output?

Trying to filter out nodes in a recursion function that iterates through a tree based on the registry property. function reduceNodesRegistry(source: any) { if (!source.registry) return source; return { ...source, children: s ...

Is there a way to generate a checkerboard dynamically with the help of jQuery?

I've made some progress so far, but I'm facing a challenge where I need to push 8 <td> elements into 8 different <tr> elements without hardcoding anything or modifying the HTML directly. Any help would be appreciated! JavaScript v ...

Angular's implementation of a web socket connection

I am facing an issue with my Angular project where the web socket connection only opens upon page reload, and not when initially accessed. My goal is to have the socket start as soon as a user logs in, and close when they log out. Here is the custom socke ...

Can Express not use await?

Why am I encountering a SyntaxError that says "await is only valid in async function" even though I am using await inside an async function? (async function(){ 'use strict'; const express = require("express"); const bodyParser = ...

What is the reason behind the undefined value of "this" in this particular class method?

I have scoured the depths of the internet in search of a solution, but I am still grappling with an issue related to a JS class I am developing for a Micro Service (still learning as I go). When attempting to call a method within a class on an instantiate ...

Is it possible to retrieve information from the parent in a Cloud Function?

How can I properly assign the name value inside the parent to a const? exports.myFunction = functions.database.ref('/messages/{pushId}/likes') .onWrite(event => { const name = event.parent.data.val().name; // This approach doesn't ...

Update data in the datatables using values from an array list

Currently, I have two HTML files where I am loading data using JSON and then applying jQuery datatables to them. Now, I need to refresh the data with new parameters. For example: JSON: [ {"name":"jon","sales":"100","set":"SET1"}, {"name":"charlie","sale ...

Select checkboxes by clicking a button that matches the beginning of a string in JavaScript

I have a form with a list of users and checkboxes below their names. Each user has a button that should select all checkboxes assigned to them. Below is the code for the dynamically created buttons and checkboxes. The included function takes the form name ...

Mastering AngularJS - Field Population with Blinking Placeholders

I understand that AngularJS fills in fields through their model. HTML is loaded first: <input type="text" data-ng-model="data.myValue" placeholder="example"> The JavaScript code comes next: $scope.data = {}; $scope.data.myValue = 'hello my v ...

What is the reason for the addEventListener function not being able to access global variables?

I have set up an event listener function to utilize popcorn.js for displaying subtitles. Additionally, I have created functions that are unrelated to popcorn.js outside of the event listener and declared a global variable array. However, when attempting ...

Fuzzy picture utilizing <canvas>

Working on translating a webgame from Flash to HTML5 with pixel art sprites, I've noticed that the canvas appears blurry compared to Flash where pixels are more defined. <!DOCTYPE html> <html> <body> <canvas id="c" style="bor ...

Do you think it's feasible to configure cookies for express-session to never expire?

Is there a way to make cookies never expire for express-session? If not, what is the maximum maxAge allowed? I came across some outdated information on setting cookie expiration on SO (over 10 years old) and here on express, which mentions a maxAge of 1 y ...

Angular alert: The configuration object used to initialize Webpack does not conform to the API schema

Recently encountered an error with angular 7 that started popping up today. Unsure of what's causing it. Attempted to update, remove, and reinstall all packages but still unable to resolve the issue. Error: Invalid configuration object. Webpack ini ...