Angular identifies when a user navigates away from a page

Currently, I am utilizing Angular 1.5 along with ui-router. My goal is to identify when a user exits a route. The code snippet I have at the moment looks like this:

$scope.$on("$stateChangeSuccess", function () {
      if (!$scope.flag) {
        //...
        $scope.do_work(reason);
      }
    });

Unfortunately, this approach is not entirely effective because upon navigation to the said route, $scope.flag is already set to false, causing the function to execute incorrectly. Is there a conventional method to trigger a function only when a user leaves a specific route and not when they enter it?

Answer №1

If you want to manipulate the state of your application while transitioning out, consider utilizing the onExit hook provided by ui-router. Keep in mind that it does not allow access to the $scope.

To work around this limitation, I suggest creating a service to store shared data. Update this shared data within the onExit hook of your desired state. This way, you can then access the same service from your controller.

$stateProvider.state("contacts", {
  template: '<h1>Dummy Template</h1>',
  controller: 'myCotroller',
  onExit: function(sharableService){
    //... perform actions using the sharableService variable...
  }
})

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 variable remains undefined, despite the fact that the code executes correctly in a different location

I'm currently working on a multiplayer game in three js and integrating socket.io for real-time communication. I have all the player characters stored in an array called players on the server side. When each client connects, I send them the list of p ...

Tips on updating route and content dynamically without triggering a page reload while ensuring search engine indexing compatibility

I am curious to find a way to change the URL displayed and have it reflect different content on the page, all while ensuring that it is search engine friendly for indexing by robots. I have experimented with using AJAX for dynamic data loading and angular ...

Are there Alternatives for Handling Timeout Exceptions in Selenium WebDriver?

Currently, utilizing Selenium WebDriver with node.js to scrape extensive weather data spanning multiple decades from a site that loads only one day's worth of data per page at full resolution. The process involves navigating between URLs and waiting f ...

Is it possible to combine the outcomes of a SQL query that produces numerous entities with identical identifiers?

Currently working on my first Node.js API project. Within the '/posts' endpoint, I am receiving data in this format: [ { "POST_ID": 1, "POST_TITLE": "Post N.1", "POST_DESCRIPTION" ...

The characteristics of angular js Service/Factory and how they influence functionality

I'm seeking clarification on the behavior of AngularJS, especially in terms of JavaScript. In my code, I have a controller that has an Angular factory injected into it. Here's a snippet from the controller: $scope.localObjCollection = myObjFac ...

You must include an argument for 'model' in the Angular service

My service requires an id parameter for a route, but when I tried to access the route with the id, I encountered the error mentioned above. Any suggestions on how to resolve this issue? https://i.sstatic.net/FEcqo.png #request const apiBaseUrl = `${envir ...

Chrome is blocking my ajax cross-origin request, causing it to be cancelled

I have been working on a Google Chrome extension and encountering an issue with my ajax requests. Every time my extension sends a request, it ends up getting cancelled for some unknown reason. The following code snippet seems to be functioning properly: ...

React-Redux Error: The function this.props.AppendCharacter is not defined

I have been looking for a solution to my issue but couldn't find anything that matches it. I am working on creating a calculator app using React & Redux, and whenever I click on one of the number buttons, I receive an error message saying "this.props. ...

Cookies are failing to be saved upon reloading the page

I found this snippet of code $(document).ready(function () { var d = new Date(); var newMinutes = d.getTimezoneOffset(); var storedMinutes = getCookieValue("tzom"); if (newMinutes != storedMinutes) { setCookie("tzom", newMinutes) ...

Create the correct structure for an AWS S3 bucket

My list consists of paths or locations that mirror the contents found in an AWS S3 bucket: const keysS3 = [ 'platform-tests/', 'platform-tests/datasets/', 'platform-tests/datasets/ra ...

Why are static PropTypes used in ReactJS and do they offer any solutions or are they merely a recurring design choice?

While delving into the code base of a web application, I came across some static PropTypes that left me questioning their purpose and necessity. Here is a snippet of the code in question: static propTypes = { fetchCricketFantasyPlayers: PropTypes.fun ...

What is the best way to create a unique custom control in Javascript, potentially utilizing jQuery?

My goal is to develop a custom control using JavaScript that includes methods, properties, and events, and can be rendered within a div element. For example, one such control could be a calendar. It would display in a div, with customizable properties for ...

Is it possible to change all text to lowercase except for URLs using .tolowercase()?

Currently, I am facing a challenge with my Greasemonkey script. The use of .tolowercase() is causing all uppercase letters to be converted to lowercase, which is disrupting URLs. I have explored alternatives like .startswith() and .endswith(), considering ...

Transform JSX into JSON or a string, then reverse the process

I am looking to store the state of a React Component in a database. Json.stringify(myComponent); However, when I attempt to reuse the component using JSON.parse, I encounter Error: Objects are not valid as a React child (found: object with keys {type, k ...

Error in table layout caused by asynchronous .get jQuery function

I am facing a challenge in populating a timetable with specific information for each cell from a database. The table is being dynamically refreshed using the following function: function refreshTable() { //Form values var park = $('#Park&apos ...

What is the best method for incorporating jQuery code into a separate file within a WordPress theme?

I'm fairly new to working with Javascript/jQuery, so please be patient with me. Currently, I'm in the process of creating a custom WordPress theme where I've been using jQuery to modify the main navigation menu generated in my header file ( ...

Angular Editable Pop-up

I have implemented Xeditable in my AngularJS application to allow users to modify table values on the fly without the need for buttons. I use the blur attribute to quickly submit changes inline. <a href="#" buttons="no" blur="submit">{{ myValue }}&l ...

The React page is stuck in a perpetual cycle of reloading every single second

After developing an invoice dashboard system using React, I encountered a recurring issue with a similar version of the app built on React. Even after commenting out all API calls, the useEffect(), the page kept reloading every second. Any advice or sugge ...

Optimizing AngularJS for speed

Looking for advice on optimizing performance for a project that involves displaying a large number of records. Here is the data structure: SERVERS (+- 15 per page) WEBSITES (+- 20 per server) USERS logged in with your STATUS (+- 500 per website) What ...

How to create a Bootstrap panel that collapses on mobile devices and expands on desktop screens?

Is there a simple way to remove the "in" class from the div with id "panel-login" when the screen size is less than 1199px (Bootstrap's xs, sm, and md modes)? I believe JavaScript or JQuery could be used for this, but I'm not very proficient in e ...