transferring information between controllers after successful SSL connection

My goal is to efficiently pass data between controllers after each successful HTTP request. This is the current hierarchy:

<div ng-controller="ParentCtrl as parent">
   <div ng-controller="ChildOneCtrl as chi1"></div>
   <div ng-controller="ChildTwoCtrl as chi2"></div>
   <div ng-controller="ChildThreeCtrl as chi3"></div>
</div>

The loading of data in each subsequent controller depends on the success of the previous one.

ChildOneCtrl:

function ChildOneCtrl ($scope, sharedService) {

   var chi1 = this;

   sharedService.getChildOneData()
       .then(function (res) {
            $rootScope.$emit('childOneDataEmited', res.data);
       }).catch(function (err) {
           console.log(err);
       });
}

ChildTwoCtrl:

function ChildTwoCtrl ($scope, $rootScope, sharedService) {

   var chi2 = this;

   var onEmitChildOne = $rootScope.$on('childOneDataEmited', function (event, data) {
        getData(data);    
   });

   $scope.$on('$destroy', onEmitChildOne);

   function getData(data){

       var chi1Data = data;

       if(chi1Data.uEnabled){
           sharedService.getChildTwoData()
              .then(function (res) {
                  $rootScope.$emit('childTwoDataEmited', res.data);
              }).catch(function (err) {
                 console.log(err);
              });
       }
   }
}

ChildThreeCtrl:

function ChildThreeCtrl ($scope, $rootScope, sharedService) {

   var chi3 = this;

   var onEmitChildThree = $rootScope.$on('childTwoDataEmited', function (event, data) {
        getData(data);    
   });

   $scope.$on('$destroy', onEmitChildThree);

   function getData(data){

       var chi2Data = data;

       sharedService.getChildThreeData()
          .then(function (res) {
               //to do some data manipulation
               console.log(res)
               console.log(chi2Data)
          }).catch(function (err) {
              console.log(err);
          });
   }
}

Although this solution works, I anticipate changes in the hierarchy that may make it more complex. I am looking for a more efficient way to handle data passing without relying too heavily on events.

Answer №1

Is it possible to share the data itself using the sharedService?
Once you receive the data from the first controller, simply assign it to a shared variable in the sharedService, and in the child controller (second one), set up a watch for this shared variable like this:

function ChildOneCtrl ($scope, sharedService) {

   var chi1 = this;

   sharedService.getChildOneData()
       .then(function (res) {
            sharedService.sharedData = res.Data;
       }).catch(function (err) {
           console.log(err);
       });
}

function ChildTwoCtrl ($scope, $rootScope, sharedService) {

   var chi2 = this;

   $scope.watch('sharedService.sharedData', function(newValue) {
         // Perform actions such as calling another endpoint using http.
   });
}  

I haven't tested it, so it might fail, but the concept is to share data through a service.

UPDATE
Another approach could be to have multiple then() functions:

function sharedService($q, $http) {
   var service = {
       sharedData1Promise: { then: function() {} },
       sharedData2Promise: { then: function() {} },
       sharedData3Promise: { then: function() {} },
       getSomeData1: getSomeData1
   };

   function getSomeData1() {
       sharedData1Promise = $http.get( /* insert url here */ );
       return sharedData1Promise;
   }

   function getSomeData2() {
      sharedData2Promise = $http.get( /* insert url here */ );
      return sharedData2Promise;
   }

   function getSomeData3() {
      sharedData3Promise = $http.get( /* insert url here */ );
      return sharedData3Promise;
   }

   return service;
}

function ChildOneCtrl ($scope, sharedService) {

   var chi1 = this;

   sharedService.getSomeData1()
       .then(function (res) {
            /* perform actions */
       }).catch(function (err) {
           console.log(err);
       });
}

function ChildTwoCtrl ($scope, sharedService) {

   var chi2 = this;

   sharedService.sharedData1Promise
       .then(function (res) {
           sharedService.getSomeData2();
           /* perform actions with data received from the first child calling getSomeData1 method */
       }).catch(function (err) {
           console.log(err);
       });
}

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

Retrieving information from MongoDB in an Express.js route handler

I'm trying to create a validation function that can check for the existence of a mongo_id. I've managed to write the function, but I'm struggling to pass the result back to the calling route. Below is the code for the function, based on an ...

"Issues arise when trying to use a Javascript button in conjunction with Bootstrap 4

When creating dynamic divs on a modal form with a close button to destroy them, everything was working fine. However, when I added a button to add new divs/forms items, the close button callback was not being triggered and instead closed the modal without ...

An issue occurred while serializing or deserializing, specifically with the JavaScriptSerializer and

I am facing an issue while trying to retrieve images from my database. The process works smoothly with small images, but when attempting to do the same with the default Windows 7 images (Desert, Koala, Penguins, Tulips, etc.), I encounter an error: "Err ...

Implementing line breaks in JSON responses in an MVC application

I am looking to show a JavaScript alert with line breaks using the message returned from a controller action that returns JSON result. I have included "\n" in the message for line breaks. Below is the code snippet from my controller: [HttpPost] publ ...

Are iFrames being utilized for third-party applications?

I am looking to create a web application that can be extended by other developers with their own applications. Would using iFrames, similar to how Facebook does it, be the best approach? Is this considered a good practice in web development? Are there a ...

Filter a Vue list based on a checkbox that can be either checked or unchecked

I am currently working on my Vue app and aiming to filter a list to display only entries that have been moderated. However, I am encountering an issue where when the checkbox is checked, I receive all the results that are true, and when the checkbox is un ...

What is the process for removing a document attribute in Sanity iO?

I have a collection of objects within my Sanity Document named Images which includes Comments An example comment object in the comments array looks like: { "_key": "6510dc79cf8b", "comment": "Hello world" ...

What is the best way to retrieve the value of an nth column in a table using

Is there a way to retrieve the value of a specific column in a table? For example, I want to get the value of the 2nd column. I have no trouble getting the first one using this method - it works perfectly fine. However, when I try to retrieve the value of ...

Positioning Firefox absolutely within a table-cell element is possible

Interestingly, it's not Internet Explorer causing me trouble this time, but Firefox. Here is the Fiddle link for reference: http://jsfiddle.net/EwUnt/ The purpose of this table is to highlight both the row and column of the cell where the cursor is ...

A JavaScript functionality that accepts an array as an argument

Currently, I'm in the process of developing a JavaScript function that accepts an array as an argument and returns the first item in the array. The function should be able to handle arrays of any size. While my current implementation seems to be effec ...

Encountering a syntax error when using a JSONP callback in AngularJS

Assistance Needed some.factory('homeService', ['$http', function($http){ return { getEvents : function(url) { return $http.jsonp(url); } } }]); Instructions homeService. ...

The audio stops when the ngaudio screen is clicked

When it comes to playing audio using the ngAudio service in AngularJS 1, the following code snippet is commonly used: $scope.audio = ngAudio.load("abc.wav"); $scope.audio.play(); However, some users have reported that after the sound is played, clicking ...

Troubleshooting the issue of 'is not a function' in browsers when using TS Namespaces

Currently diving into the world of TypeScript, I've embarked on the journey of organizing my code into separate files. My primary file is structured as follows: // calculator.ts namespace Calculator { console.log(Calculator.operate(1,2,"+")) } In ...

HTML stubbornly resists incorporating Javascript [UIWebView]

Currently, I am facing an issue while trying to animate a color property using jQuery 1.7.1 and the jquery color plugin downloaded from this link. I have ensured that all necessary files are included and part of the build target. Here is a simplified versi ...

Utilize localstorage with Redux and Next.js to initialize the state

Having an issue when attempting to populate the initial state from local storage in order to create a store. I encountered the following error message: ReferenceError: localStorage is not defined Here is my store configuration: const store = createStore(r ...

The play button in the customized React AudioPlayer may sometimes need to be tapped twice in order to start

I've encountered an issue with my simple audio player (React/Vite) that transitions to the next track automatically or manually. Everything seems to be functioning correctly except for the initial press of the play button. The player opens with the pa ...

Tips for keeping data on a page up-to-date using Node.js and Express

Currently delving into the world of Node.js and Express, I am immersed in a project that involves pinging websites and exhibiting the results on a web page. Leveraging HoganJS for templating as well. My primary focus is to decipher the steps necessary to m ...

The radio button's checked property is set to true, but the tick mark is not visible

I am currently developing a modal form using php, in which I have included the following radio buttons. Below is the php form I have created: <div class="form-group"> <div class="form-row"> < ...

Issue with AngularJS controller not functioning properly in the application

Hey there, hope everyone is doing well! I recently started learning AngularJS and things were going smoothly. I've been creating controllers and using them in my webpages with no issues. However, I've hit a roadblock when trying to create a contr ...

capturing webpage content with javascript for use in a screenshot

Is there a way to capture a screenshot of a webpage using JavaScript and utilize the canvas tag for this purpose? I attempted to use the html2canvas plugin in the past, but found it lacking in power. I would like to achieve this without relying on extern ...