Inform promise angular to eliminate callback

When it comes to notifying multiple controllers of external changes from a service, one method is to utilize a deferred object. By calling notify on the deferred object and registering a callback on it, controllers can receive updates.

For example:

// Code in the service
$timeout(function() {
    defered.notify('In progress')}
, 0)

// Code in the controller
var promise = myService.promise
promise.then(function(success) {
    console.log("success");
}, function(error) {
    console.log("error");
}, function(update) {
    console.log("got an update!");
}) ;

The question now arises: Is there a way to remove the notify callback when the controller is destroyed?

Answer №1

UPDATE BASED ON ADDITIONAL QUESTION CONTEXT

If you want to ensure the $timeout is canceled when the controller is destroyed, follow these steps:

First, create the $timeout like this...

$scope.myTimeout = $timeout(function() {
                defered.notify('In progress')}
            , 0);

Then, in the controller, include the following:

$scope.$on('$destroy', function () {
    $timeout.cancel($scope.myTimeout);
});

In my experience, this method effectively cleans up any lingering processes.

If you only want to clear the notify callback itself, consider using $broadcast or $emit as suggested (refer to @Pio's answer). For a detailed comparison between them, check out this guide.

Understanding the distinction is crucial!

Answer №2

To achieve a similar behavior, you have the option to utilize $on, $broadcast, and $emit in AngularJS.

All you need to do is $broadcast(name, args); an event and then register a listener with $on(name, listener);.

When you receive your data, simply broadcast to notify everyone that you have obtained it.

$broadcast('gotTheData', actualDataObject); 

Afterwards, in your controllers:

 $on('gotTheData', function(event, actualDataObject)
     {
         ... update controller data ...
      });

It's important to note that although I only added one actualDataObject in this example, you are able to pass multiple arguments from $broadcast to $on. For further information, please refer to the documentation (provided in the link above).

In response to the comments on @Scott's answer, an essential aspect you highlighted is the necessity to unregister the $on when destroying the controller using the "Returns a deregistration function for this listener." method that can be found within the documentation of $on. There is a specific question addressing this issue: How can I unregister a broadcast event to rootscope in AngularJS?.

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

Objects cannot be rendered inside JSX. An error is thrown stating that Objects are not allowed as a React child, with the specific object being [object Promise]

Within my React project, I have a Class-based component that serves as a child component. The state it relies on is passed down from a parent component. Within the JSX of this component, there is a map function that iterates over a platformsList array. Whi ...

The console is throwing an error: ReferenceError: The variable $ has not been defined

I am having issues when trying to dynamically add a div upon selecting a checkbox in a Django template. The error message Uncaught ReferenceError: $ is not defined keeps appearing in the console. Here is the template code: {% extends 'base_layout.htm ...

What is the best way to show and hide the information in a FAQ section when each one is clicked?

const faqItems = document.getElementsByClassName("faq-question"); const faqContents = document.getElementsByClassName("faq-content"); for (item of faqItems) { console.log(item); item.addEventListene ...

Ways to resolve eslint typedef error when using angular reactive forms with form.value

I am facing an issue with my formGroup and how I initialized it. Whenever I try to retrieve the complete form value using form.value, I encounter an eslint error related to typecasting. userForm = new FormGroup<user>({ name: new FormControl<st ...

Triggering AWS Lambda functions with SQS

Utilizing AWS and SES for sending emails and SMS through a Lambda function using NodeJs. I need to make more than 1k or 500 REST API calls, with the average call taking 3 seconds to execute a single lambda function request. It is essential to process mul ...

Is there a way to incorporate a delete button for each li element that is included in my list?

I have successfully implemented a to-do list where clicking on an item strikes a line through it and there is a delete button that works. However, I am looking for assistance on how to create a delete button for each newly added li item. var button = do ...

Search for elements within the database by using the recursive feature of M

I am working on a search query to retrieve 'n' number of videos from a collection. The user has primary, secondary, and tertiary language preferences (Tamil(P), Hindi(S), English(T)). My goal is to first search for videos in the primary language, ...

Is it possible for Cypress to execute test files that are imported from outside of the Cypress folder

Currently, I am developing an E2E test framework using Cypress and encountered an issue while trying to import spec files from locations outside the traditional Cypress directory structure (which includes directories for fixtures, integration, plugins, and ...

How to Conceal Axis Label in an HTML5 Canvas Line Chart

Is there a way to hide the x-axis label from a line chart without hiding the y-axis label as well? I tried using scaleFontSize: 0,, but that ended up hiding both axis labels. I only want to hide the x-axis label. var lineOptions = { ///Boo ...

Switching back and forth between different rows within a table

Currently, I am just starting out with AngularJS (1.5) and I have come across a challenge that I am hoping to get some assistance with. I have a table that is generated dynamically and for each row, I need to add a down arrow in the first column. Based on ...

Obtain the node identifier within the Angular UI Tree component [angular-ui-tree]

Utilizing Angular UI tree to create a relationship between items and categories has been successful in the default setup. However, a new requirement has emerged to incorporate node/section numbering within the tree for managing hierarchy. I attempted to i ...

Distinguishing between el and $el in Backbone.Js: What sets them apart?

I spent the entire afternoon struggling with this particular issue, but finally managed to resolve it. It ended up being a mix-up between assigning el and $el. Can anyone clarify the distinction between these two terms and provide guidance on when to use ...

I am having difficulty retrieving all the cssRules for certain pages

Attempting to retrieve all CSS rules using JavaScript has yielded varying results. For instance, on StackOverflow, the code used is: console.log( document.styleSheets[1].href,'rules', document.styleSheets[1].cssRules,'Should be css rules, ...

When implementing dynatable with Meteor, the outcomes may vary between the demonstration in a fiddle and the actual application

Here is the fiddle I created for this question: https://jsfiddle.net/ereday/82wzwem8/2/ In the fiddle, you'll notice that the table header has a green background. Now, let me share the code snippet from my meteor project: simple-todos.html <head ...

What are the most effective methods for enhancing this perspective?

I currently have a functional view that I would like to enhance for better optimization. It is currently quite convoluted and I am unsure of the best approach to simplify it. Should I use functions in the controller or create a directive? The main area ...

Increasing variable in angular template (nested ng-repeat)

I am facing a similar situation as described in the example below, and I need to generate a serial number for each row independently for each mark record. Here is the Java script Object structure: $scope.childsList = [ { id:12346, ...

Getting the present location on Google Maps for the web: A step-by-step guide

As a newcomer to this API, I have successfully generated an API key but am unsure of how to implement Google Maps. Despite my extensive research, I have been unable to find a solution that works for me. I am seeking assistance in locating users or devices ...

Is it necessary to utilize container or container-fluid within the grid system layout?

While similar questions may already exist on Stackoverflow, I believe the exact answer has yet to be found. Many suggest: "You should nest .col within .row, and ensure that .row is inside of .container." However, this concept still eludes me. I underst ...

How to Change Text When Accordion is Expanded or Collapsed using Javascript

Help needed with JavaScript accordion menu for displaying indicators in front of section headers. The goal is to show a (+) when collapsed and (-) when expanded. The current code only changes on click, not based on the section's state. Looking for fre ...

An issue has been encountered in the OBJLoader module within the THREE.JS library

I've been delving into the teachings of the Three.js library through the book "Learning Three.js: The JavaScript 3D Library for WebGL" and I've also downloaded the example sets from the corresponding GitHub repository https://github.com/josdirkse ...