Using a Promise to signal the completion of certain tasks

In our application, we have multiple controllers assigned to different tabs/pages. I am looking for a way to signal the completion of a task in one controller so that it can be used in another controller. I believe Promises are the solution for this, and I am trying to understand how they work.

I experimented with http://jsfiddle.net/ExN6Q/ and achieved the desired functionality, but I am not entirely satisfied with how the services were implemented.

For example, consider the following HTML structure:

<div ng-app="myApp">
    <div ng-controller=myController1>
        Fill in this field: <input type="text">
        <input type="submit" value="Done" ng-click="submit()">
    </div>
    <div ng-controller=myController2 ng-show="done1">
        And this field: <input type="text">
        <input type="submit" value="Done" ng-click="submit()">
    </div>
    <div ng-controller=myController3 ng-show="done2">
        As well as this field: <input type="text">
        <input type="submit" value="Done" ng-click="submit()">
    </div>
</div>

and the corresponding controllers:

my_module.controller('myController1', function ($scope, Done1Service) {
    $scope.submit = Done1Service.done;
});

my_module.controller('myController2', function ($scope, Done1Service, Done2Service) {
    $scope.done1 = false;
    $scope.submit = Done2Service.done;
    Done1Service.get_promise().then(function () {
        $scope.done1 = true;
    });
});

my_module.controller('myController3', function ($scope, Done2Service, Done3Service) {
    $scope.done2 = false;
    $scope.submit = Done3Service.done;
    Done2Service.get_promise().then(function () {
        $scope.done2 = true;
    });
    Done3Service.get_promise().then(function () {
        alert("Congratulations, you're done!");
    });
});

While I am happy with the result, I feel that the implementation of the services is too repetitive. Is there a better approach, such as creating a single common service and instantiating it three times? Should I rename the get_promise function to make it more descriptive?

Answer №1

Your services are currently set up as one-time deals due to the inability to reset promises. To address this issue, I suggest implementing a single centralized EventBus service for all controllers to communicate through. For example, the first controller can send a 'step1completed' message on the bus, which would then be received by the second controller to execute its tasks and trigger a 'step2completed' event, and so on.

If there are multiple identical processes that need to run simultaneously, you could consider creating distinct EventBus instances to serve as independent communication channels for specific sets of objects.

Angular already provides the ability to emit or broadcast events through scopes. Take a look at $emit and $broadcast.

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

Exploring the world of Restify: Mastering the art of sending POST

Having trouble reading the body of a request while trying to create an API with Restify. Snippet from main.js: 'use strict'; const perfy = require('perfy'); perfy.start('startup'); const restify = require('rest ...

Retrieving information from a text document by means of data-src with the assistance of jQuery

Trying to extract text from a .txt file using jQuery while utilizing Bootstrap. New to web design with some coding experience. Button in HTML: <button type="button" class="btn btn-primary-outline-btn text-btn" data-toggle="modal ...

When crafting an XPATH expression, I am able to navigate within the #document element. Within this element, I must specify the path to the HTML body of my web page

I need assistance with my HTML page, can someone please help? Here is the XPath code I am using: (//span[text()='Information']//following::div[contains(@class,'edit-area')])[1]/iframe However, when I run my script, it says that there ...

Manually sending the form via Ajax for submission

I'm facing an issue where I am trying to utilize ajax to call a servlet upon form submission. However, the ajax call is not being triggered and the page ends up reloading. To solve this problem, I have set up a manual trigger for the form submission, ...

Execute an AJAX call to remove a comment

Having some trouble deleting a MySQL record using JavaScript. Here is the JavaScript function I am trying to use: function deletePost(id){ if(confirm('Are you sure?')){ $('#comment_'+id).hide(); http.open("get","/i ...

Transforming S3 Buffer Information into a PDF Document

Utilizing an express route to fetch the s3 object through the AWS SDK: router.get('/myRoute', (req, res) => { const s3 = new AWS.S3({apiVersion: '2006-03-01'}); s3.getObject({Bucket: 'my-bucket', Key: 'my-key'}, ...

Content will be loaded only after the user clicks on the item

On my blog, I have a share button that displays different social media platforms when clicked. However, the page takes longer to load due to fetching data from multiple servers like Facebook and Twitter. Is there a way to use jQuery to make these buttons l ...

"Effortlessly move elements with HTML5 drag and drop functionality from either direction

I'm working on an application that requires Html5 Drag and Drop functionality, which is currently functioning well. However, in the app, there may be instances where a dropped item is no longer needed and I want to allow users to re-drag and drop it b ...

Exploring the depths of JSON: Unraveling the secrets of reading dynamic object data

Currently, I am receiving a JSON file from another app and my goal is to parse it in order to extract the data contained within. The JSON includes user-defined dynamic data with changing key/value pairs, which has left me feeling uncertain about how to eff ...

Troubleshooting the issue with ajax loadXml callback functionality

My table is empty and I can't figure out where the mistake is. I want to use the console to debug, but I'm not sure how. Update: I found a working sample here http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_xml2. I used similar code, bu ...

Angular ng-repeat not populating the list properly, causing a collapse not to display

Currently, I am working on developing an app using Angular.js and Bootstrap UI, but I have run into a problem with a collapse navigation feature. The issue I am facing is that I have an ng-repeat that should be functioning properly. However, when I click ...

How to trigger a JavaScript function using a button click

I've been struggling to figure out why my JavaScript code isn't functioning properly within Ionic. Can anyone guide me on how to store a number in a variable, display that variable, and increment it when a button is clicked? I have successfully ...

The Art of Mass Updating Embedded Documents in MongoDB

Struggling with updating an embedded document in MongoDB using Bulk updates on version 3.0. Any assistance would be greatly appreciated. ...

Guiding a WordPress Form Submission to a Different Page

I'm currently using WordPress to create a form with the following code: [contact-form][contact-field label='What message would you like to send?' type='textarea' required='1'/]Word Limit: 50 words[contact-field label=&ap ...

Eliminate an item from a JavaScript array

I am trying to remove a specific element from a JavaScript array. The element I need to remove is the one with the value of 'NT'. In my HTML input, I have: <input type="text" id="caseType" size="50"/> To populate it, I use: var c ...

Implementing multiple condition-based filtering in React Native for arrays

I am looking to apply multiple filters to an array based on certain conditions defined by toggling switches. The issue arises when toggling two or more switches simultaneously, resulting in an empty array. My goal is to retrieve an array containing the tru ...

Retrieve the keys of a JSON object from an unfamiliar JSON format

I have a challenge involving an algorithm where I need to extract all keys (including nested objects and arrays of objects) from a JSON file with unknown structures and store them in one array. { "key": "value to array", "key": [{ "key": { "k ...

Variations in output observed from angular function across various sections within DOM

After fetching a list of permissions in the background, my goal is to display a page or an error message based on whether the user has the required permissions. I encountered an unusual issue where both sections of the page are being displayed despite hav ...

Getting URL parameters in NextJS when using Custom Document can be achieved by accessing the `ctx`

Currently, I am utilizing NextJS for generating SSR pages that are language-specific. I want to specify the lang property to indicate the language of the text. Here's what I have done so far: import Document, { Html, Head, Main, NextScript } from &qu ...

The framework of AngularJS modules

As I delve into structuring multiple modules for our company's application, I find myself at a crossroads trying to design the most optimal architecture. Research suggests two prevalent approaches - one module per page or a holistic 'master' ...