What is the mechanism behind $scope.$on activation and $destroy invocation?

Seeking an explanation on the functionality of $scope.$on and how $destroy works in two separate controllers. When switching routes, a new controller is invoked, leading to the activation of $destroy. Could someone shed some light on how $interval is initialized? It appears to be defined as a variable within promiseA but still initializes itself. These lines of code were directly copied for compliance purposes, any clarification would be greatly appreciated.

var myApp=angular.module('myApp',['ngRoute']); 
        myApp.controller('myController',function($scope){


        });
        myApp.controller('firstPage',function($scope,$interval){

            $scope.thisMessage="First Message";
            $scope.firstcall=function(){
                var promiseA=$interval(function(){

                        console.log("First Page");
                    },10000);
                $scope.$on('$destroy',function(){
                    $interval.cancel(promiseA);
                });
            }
            });
        myApp.controller('secondPage',function($scope,$interval){
            $scope.thisMessage="Second Message";

            $scope.thisMessage="Second Message";
            $scope.secondcall=function(){
                var promiseB=$interval(function(){

                        console.log("Second Page");

                },10000);
                $scope.$on('$destroy',function(){
                    $interval.cancel(promiseB);
                });
            }
        });

        myApp.config(function($routeProvider){
            $routeProvider.when("/",{
                templateUrl:"First.html"
                })
            .when("/second",{
                templateUrl:"Second.html"
            });
        });

Answer №1

In a nutshell, by using the $scope.$on function in Angular, you can subscribe to both internal and custom events. You can trigger these custom events yourself using the $emit and $broadcast services. The $destroy event is specifically triggered when a controller is being destroyed, giving you an opportunity to handle any necessary cleanup tasks.

For more detailed information on this topic, refer to Angular's documentation here.

Since each route has its own controller in Angular, transitioning between routes involves instantiating and destroying controllers. This process triggers the $destroy event that you can listen for.

I suggest exploring the $off method as well, which allows you to unsubscribe from events to prevent memory leaks or unexpected behavior. Although there may not be official documentation available, you can subscribe to an event like this:

$scope.$on('customEvent', someFunction);

And unsubscribe using this syntax:

$scope.$on('$destroy', function() {
    $scope.$off('customEvent', someFunction);
});

It's worth noting that unsubscribing within the $destroy listener is considered a best practice, although it's not compulsory.

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

Backend server encountered an issue with processing punycode

[ALERT] 18:13:52 Server Restarting Prompt: C:\Code\MERN_Projects\podify_app\server\src\db\index.ts has been altered (node:22692) [DEP0040] DeprecationWarning: The punycode module is outdated. Consider utilizing a modern a ...

When utilizing Vue JS, each key value of one computed property can trigger another computed property to run

I have a computed property: getRelatedItem () { return this.allItems.find((item) => { return item.id === this.currentSelectedItemId }) }, Here is an example of the output: relatedItem:Object -KQ1hiTWoqAU77hiKcBZ:true -KQ1tTqLrtUvGnBTsL-M:tr ...

Routing in Next.js to create custom URL slugs for usernames, like (site.com/username), is a

I have a requirement to create username pages on my website, where each username will have its own page like site.com/jack The current folder structure I am using is pages > [user] > index.js, but this setup causes issues when someone tries to acces ...

A guide to replicating HTML using AngularJS

I am attempting to replicate HTML content using AngularJS. While I was successful using jQuery, it caused conflicts with Angular. Therefore, I aim to achieve the same result using AngularJS. Here is the code I have written: function printContent(el){ ...

A method for integrating a Child Component into a UI5 parent application without specifying them in the manifest.json

Seeking advice on loading a Child Component in a UI5 parent app. Currently working on creating a Fiori Launchpad that can dynamically load other apps as Child Components. I have been exploring methods mentioned in an insightful post at However, the imple ...

Error message: "Root resolution error encountered". Need assistance in granting watchman access?

After setting up a react-native starter project, I was prompted to allow watchman access to my system's files. Unfortunately, I declined and now whenever I try to run the folder, I encounter the following error: Error: unable to resolve root /Users/ck ...

Guide on implementing EdgesHelper with imported Collada model using three.js

Having some issues while using the EdgesHelper on a loaded Collada model in three.js: Applying edges to the entire model geometry, Misalignment and scale discrepancies between the Collada model and the generated edges. View Demo var controls, scene, ca ...

After using driver.execute_script, the variable results in nil

Attempting to retrieve a lengthy string of URLs separated by commas is proving challenging. The code functions correctly in the console, but when running the script, the ruby variable urls_list remains nil. require 'rubygems' require 'selen ...

IE/Firefox returning empty value for Ajax requests

After spending two days trying to solve the issue, I still can't figure out why this code is failing in IE (v11) and Firefox while working fine in Chrome. I have read many questions on similar topics involving caching problems with multiple Ajax call ...

Obtain the ClientID for a particular user control that is within a repeater's bindings

I have a collection of user controls that I am connecting to a repeater. The user control: (Example) "AppProduct" <div> <asp:Button ID="btn_details" runat="server" Text="Trigger" /> <asp:HiddenField ID="pid" ...

How does combineReducers in Redux determine which specific portion of the application state to send to the reducer?

While going through the Redux basics tutorial, I found myself a bit confused about how the code snippet below determines which part of the application state should be passed to each reducer mentioned in the combineReducers function. Does it simply rely o ...

What is the best way to invoke a Service from a Directive in AngularJS?

Every time a user clicks, a directive is triggered to change the icon for adding to their favorite list. View: <div class="col col-33"> <i class="icon ion-ios-heart-outline" favorite="place[0].objectId" on-icon="ion-ios-heart-outline" off-ic ...

Learn how to seamlessly update broken images on a webpage with a placeholder error image using the MooTools 1.2 framework

Currently working on a project with PHP, MySQL and utilizing Mootools 1.2 as the JavaScript framework. I am trying to find a way for all broken images to automatically be replaced with a designated error image. Any suggestions on how I can achieve this? ...

The backend API does not receive the correct value from the checkbox

I'm having an issue with my registration page in ReactJS. There is a checkbox field called isadult. After clicking on the Register button and saving the data to a MongoDB database, the value of isadult shows up as [Object object] instead of True or Fa ...

When I try to send data from my Node.js application to my MySQL database, the information does not

I am currently working on developing a registration and login page, where the user details are stored in a database for authentication during login. The registration button is meant to store user data in the database to complete the sign-up process. For t ...

Generate a Selectpicker dynamically when a button is clicked

Wanting to insert a new row in an HTML table dynamically by clicking on an add button. The new row includes a select element with the selectpicker class. Interestingly, when I remove the selectpicker class in my script to append a new row, the select eleme ...

AngularJS: When the expression is evaluated, it is showing up as the literal {{expression}} text instead of

Resolved: With the help of @Sajeetharan, it was pinpointed that the function GenerateRef was faulty and causing the issue. Although this is a common query, I have not had success in resolving my problem with displaying {{}} to show the outcome. I am atte ...

Encountering Issues with Formatting InnerHtml Text using RegEx

Technology: React.js I have been working on a custom function in JavaScript to highlight specific words within a code block. The function seems to be functioning correctly, but the highlighting isn't staying after the function is completed. Any ideas ...

Adding information to a single class that shares a common name

Currently, I have successfully implemented a row cloning scenario where multiple dynamic rows are created after confirming an inventory number from a MySQL database. However, I am facing an issue with inserting the inventory data only to the next DIV eleme ...

The menu is about to receive some custom styling

I have come across a webpage where I need to make some modifications, but I am unable to locate the script responsible for applying the inline style. This issue only seems to be occurring on the mobile version with the dropdown menu. <div class="is-dri ...