Navigating the Angular Controller life cycle

I have set up my application states using ui-router:

$stateProvider
  .state('app', {
    abstract: true,
    views: {
      'nav@': {
        templateUrl: 'app/navbar.html',
        controller: 'NavbarController',
        controllerAs: 'vm'
      },
      'main@': {
        template: '<div ui-view></div>'
      }
    }
  })
  .state('child1', {
    url: '/child1',
    parent: 'app',
    templateUrl: 'app/child1.html',
    controller: function($timeout) {
      $timeout(function() {
        alert('from child_1');
      }, 15000)
    },
    controllerAs: 'vm'
  })
  .state('child2', {
    url: '/child2',
    parent: 'app',
    templateUrl: 'app/child2.html',
    controller: 'ctrl_2',
    controllerAs: 'vm'
  })

After navigating quickly from /child1 to /child2 (before 15000 milliseconds), I still see the alert message defined in the child1 controller. Is this expected behavior?

Answer №1

Is it common for this behavior to occur?

Absolutely, this is completely normal behavior. When function references are created and passed to another function (like the $timeout service), they will remain active as long as that other function holds onto them. In the case of the $timeout service, it will maintain that reference for the specified timeout period (in this scenario, 15 seconds).

Furthermore, if the child function utilizes local variables from the parent function, those variables will persist throughout the lifetime of the child function. This concept is known as "creating a closure".

For more detailed information, you can refer to MDN JavaScript Reference - Closures

It is crucial to inform the $timeout service to cancel the timeout and release the reference; otherwise, it may outlast the controller's lifespan.

controller: function($timeout, $scope) {
  var promise = $timeout(function() {
    alert('from child_1');
  }, 15000);
  $scope.$on("$destroy", function() {
    promise.cancel();
  });
},

In the example above, the $timeout service adds a function named cancel to the promise it generates. By invoking this function in the client code, it signals the $timeout service to terminate the timeout and release the function reference.

When transitioning from the child1 state to another state with ui-router, the scope of the controller is destroyed. Therefore, the controller should monitor the $destroy event and stop the timeout accordingly.

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 getting Fullcalendar to show up on my cordova app

Currently, I am in the process of building a mobile application using ionic and cordova. My goal is to incorporate a timetable system utilizing Fullcalendar and a PHP page that showcases MySQL data in JSON format. Despite my efforts, I am encountering diff ...

Personalized tooltips for numerous data sets in Highcharts

I am currently in the process of constructing a highchart that is capable of accommodating up to five different types of data series. I have arranged similar series together, resulting in three distinct y-axes for the various series. However, I have encou ...

The JQuery File-Upload plugin remains inactive even after a file has been chosen

I am currently working on integrating the JQuery File-Upload plugin (). The issue I'm facing is that it doesn't respond when a file is selected. Here are some potential problems to consider: No errors appear in the Chrome console. Selecting a ...

Learn how to collapse a list by clicking outside of it on the document with the following code: $(document).on("click"

I want to create a collapsible/expandable menu for my website. I had a version where hovering over a category would expand the subcategory, but what I really need is for the subcategories to expand when I click on a category and remain expanded until I cli ...

Interacting between Angular.js controllers and Polymer custom elements

Incorporating Angular.js and Polymer in my project has been a challenge, particularly when it comes to the communication between Angular.js controllers and Polymer custom elements. One specific issue I've encountered involves implementing an AuthServ ...

How to iterate over the request body in Node.js using Express?

When I send a request with data in the form of an array of objects: [ {id: "1"}, {id: "2"}, {id: "3"} ] I am utilizing JSON.stringify() and my req.body ends up looking like this: { '{"id":"1"} ...

Choose an XPath selector that targets a list item within a specific div element

Currently, I am using selenium to conduct testing on a website. I have employed an XPath selector in order to locate a specific item within the HTML structure: <div id="boundlist-1051" class="x-boundlist list_cfg_cls x-boundlist-floating x-layer x-boun ...

Is it possible to track traffic using Alexa or SimilarWeb on a single-page application?

We are currently grappling with the challenge of how to effectively track traffic and user engagement within our classified sites on a single-page application built in angularJS. While we have successfully managed SEO and tracking with Google Analytics, we ...

Steps for replacing $httpProvider in a service when there is already a defined $httpProvider

Having trouble with my factory service: app.factory('sessionInjector', ['sessionService', 'stateService', '$q', function (sessionService, stateService, $q) { var myInjectorInstance = { /* ... */ }; return m ...

Issue with JSON data not functioning properly in AJAX request

I have been facing an issue with detecting whether a database entry has been successfully input. I am sending the new inserted ID and a JSON variable to an AJAX call, which works fine in all browsers but not in phonegAP. Despite that, the data is being suc ...

Importing components in real-time to generate static sites

My website has a dynamic page structure with each page having its unique content using various components. During the build process, I am statically pre-rendering the pages using Next.js' static site generation. To manage component population, I have ...

Error: React - Module not found. This issue arises when attempting to require the 'express' package from within the installed

Hello, I attempted to install the express package in a React project. However, when I try to import the package inside app.js using: const app = require("express"); I encounter 30 errors all stating: Module not found Error: Can't resolve 'x&ap ...

Toggle the image and update the corresponding value in the MySQL database upon clicking

Looking to implement a feature that allows users to bookmark pages in my PHP application using JavaScript. The concept involves having a list of items, each accompanied by an image (potentially an empty star). When a user clicks on the image, it will upda ...

Error encountered when accessing Spotify API. The requested action requires proper permissions which are currently missing. Issue arises when attempting to

I am attempting to use the spotify-web-api-node library to play a track on my application const playSong = async () => { // Verify access token with console.log(spotifyApi.getAccessToken()) setCurrentTrackId(track.track.id); setIsPlay ...

After triggering an action, I am eager to make a selection from the store

To accomplish my task, I must first select from the store and verify if there is no data available. If no data is found, I need to dispatch an action and then re-select from the store once again. Here is the code snippet that I am currently using: t ...

Upon successful completion of the Ajax call, refresh the page without causing any blinking

Hey there, I'm facing an issue with my website, I've implemented ajax to fetch data from my API, and upon successful retrieval, I need to reload the page to display the information, However, sometimes the page blinks before reloading, while oth ...

Enhancing features with jQuery's .animate() function

Can anyone help me figure out why the div on the right is not pushing itself away from the one on the left when I hover over it? I want it to move on mouseenter and return to its original position on mouseleave. The changing background colors are just ther ...

Incorporating a protected Grafana dashboard into a web application

I am looking to incorporate Grafana into my web application using AngularJS. The main objective is to allow users to access the Grafana UI by clicking on a button within my application. Setting up an apache reverse proxy for Grafana and ensuring proper COR ...

Guide to verifying Regular Expressions for text fields in JSP with JavaScript

Need help with validating the firstname using regex. The javascript code provided generates an error if the value length is 0, however, even after entering a correct firstname format based on the regex, it still shows 'First name invalid'. I susp ...

Enhance Your GoJS Pipeline Visualization with TextBlocks

I am facing challenges in customizing the GoJS Pipes example to include text within the "pipes" without disrupting the layout. Although I referred to an older response on the same query here, it seems outdated or not detailed enough for me to implement wit ...