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

Tips for creating an HTML page with the dimensions of an A4 paper sheet?

My goal is to display the HTML page in a browser while containing the content within the dimensions of an A4 size page. Additionally, when printed, the HTML page should be formatted to fit onto A4-sized paper pages. <div classNa ...

Guide to navigating to a particular component in React JS

I've designed a web application using React that doesn't contain any HTML, and I've broken down each page into smaller modules. For instance, on the main page, the first module (located at the top) contains a button that, when clicked, shoul ...

using hover/click functionality with a group of DIV elements

I have a group of DIV elements that I want to apply an effect to when hovering over them with the mouse. Additionally, when one of the DIVs is clicked, it should maintain the hover effect until another DIV is clicked. <div class="items" id="item1"> ...

implement a discount and waive tax computation specifically for Canadian customers

I have encountered a problem while developing a POS application for a client in Canada. My issue lies in the tax calculation process, where I am unsure how to handle discounts and tax exemptions properly. Here is the scenario: I have 2 items - item 1 price ...

Save picture in localStorage

Hello, I am currently working on a page where I need to retrieve an image from a JSON file and store it locally. Below is the code I have been using: <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.10.1.min. ...

The Fuel-ui module in Angular 2 fails to function properly when loaded from a different directory

We recently switched from ng-cli to Gulp for building our Angular2 project, and we are utilizing Fuel-ui. An unusual error has come up. We have incorporated Fuel-ui's alert component into one of our components. When referencing fuel-ui from node_mo ...

What are some creative ways to visually distinguish a TextField that is in readOnly mode?

I'm currently working on creating a form using the Material-UI library. I'm having difficulty figuring out how to distinguish my TextField when they are in readOnly mode versus edit mode. At the moment, they appear identical and I would like the ...

When using Node Puppeteer, if the page.on( "request" ) event is triggered, it will throw an error message stating "Request is already being handled!"

I am currently utilizing puppeteer-extra in conjunction with node.js to navigate through multiple URLs. During each iteration, I am attempting to intercept certain types of resources to load and encountering the error below. PS C:\Users\someuser ...

Performing an HTTP POST request in Angular 2

After starting my work with Angular 2 and TypeScript, everything was going great. However, I encountered an issue when working with a REST API (POST) where the console log displayed Response {_body: "", status: 204, statusText: "Ok", headers: Headers, type ...

Is the 'wait > remaining' condition ever satisfied in the throttle function of underscore.js?

Check out the library code at line 860: https://github.com/jashkenas/underscore/blob/master/underscore.js if (remaining <= 0 || remaining > wait) Under what circumstance would the second part of this statement be true? Background - This is my firs ...

What is the method for modifying the array that has been generated using Vue's "prop" feature?

According to the Vue documentation, a prop is passed in as a raw value that may need transformation. The recommended approach is to define a computed property using the prop's value. If the "prop" is an array of objects, how can it be transformed int ...

How can you apply color to {{expression}} text using AngularJS while also keeping all the text on a single line?

After writing the following code, I noticed that when I enter text into the input box, an output appears. However, I am now trying to find a way to color the output text while keeping it on the same line. <script src="https://ajax.googleapis.com/ajax ...

What is the most effective method to determine if a given string is suitable for $compile in Angular?

I am currently in the process of creating a directive that is designed to accept a "message" input which may contain HTML and nested Angular directives. In my directive's controller, I am using the following code: var compiled = $compile(message)($sc ...

Failing to retrieve the file instance upon completing the upload process to cloudinary using nestjs

I am attempting to retrieve the secure file URL provided by Cloudinary after successfully uploading the asset to their servers. Although I can upload the file to Cloudinary, when I try to view the response using console.log(res), I unfortunately receive &a ...

Exploring the functionality of Next.js with Links and routes

Currently, I am facing an issue with the popover menu in my header that displays products. The problem arises when I click on a product in the list; it navigates correctly to the path "products/some-product" regardless of the selected item. However, if I a ...

Validating emails using Vue.js

After spending a solid 24 hours working with Vue, I realize there may be some gaps in my knowledge. Despite my efforts to search for solutions, I suspect that my lack of understanding on basic principles is hindering me. One issue I've encountered is ...

Using Vue.js to add animation effects to elements

What is the best way to use the .animate function on an element in vuejs? <aside v-transition v-if="toggleMenu"> <a href="#">Haha</a> <a href="#">Nice</a> <a href="#">Menu</a> </aside> A similar piece ...

What steps should be taken to resolve the error message "This Expression is not constructable"?

I'm trying to import a JavaScript class into TypeScript, but I keep getting the error message This expression is not constructable.. The TypeScript compiler also indicates that A does not have a constructor signature. Can anyone help me figure out how ...

jQuery - Enhancing User Experience with Dynamic Screen Updates

Is there a way to update the screen height when resizing or zooming the screen? Whenever I zoom the screen, the arrows break. I'm also curious if the method I'm using to display images on the screen is effective. It's supposed to be a paral ...

Express Module Employs Promises for Returns

I have a JavaScript file for elasticsearch (could be any other database as well) that performs a simple query and uses a promise to return the data. I am using this module in my Express server (server.js) with the hope of retrieving the data, as I ultimat ...