AngularJS service for exchanging information among controllers

I am working on an AngularJS application (1.4.10) where I need to share data between two controllers.

To achieve this, I created a factory:

.factory('CardsForService', function($http, URL){
    var service = {
        "block_id": '',
        "service_id": ''
    };

    service.save_data = function(block_id, service_id){
        service.block_id = block_id;
        service.service_id = service_id;
    };

    service.get_data = function(){
        return service;
    };

    return service;
})

I set the data in the first controller:

$scope.open = function(id, type){
    console.log(id +" "+type);
    CardsForService.save_data(id, type);
    ...

And when attempting to retrieve the data in another controller, it seems to return empty:

$scope.$on('$routeChangeSuccess', function() {
    if  (algo_to_used == "service"){
        var data = CardsForService.get_data();
        console.log(data);
    } else {
    }
});

The output of console.log shows:

Object {block_id: "", service_id: ""}

However, when I use the get_data() function in the same controller as save_data(), it works fine. What could be causing this issue?

Answer №1

Revamp the Factory Here

app.factory('CardsForService', function(){
var service = {
    "block_id": '',
    "service_id": ''
};

var updateData = function(block_id, service_id){
    service.block_id = block_id;
    service.service_id = service_id;
};

var retrieveData = function(){
    return service;
};

return{
   updateData:updateData,
   retrieveData:retrieveData
}});

Now in the controllers

app.controller('FirstCtrl',function(CardsForService){
    CardsForService.updateData(id, type);
});

app.controller('SecondCtrl', function($scope, CardsForService){
    $scope.data = CardsForService.retrieveData();
});

Answer №2

It seems like there might be a timing issue at play here. The data obtained from a service similar to this one may not update in real time. Below is a snippet that offers a visualization to help illustrate this.

var app = angular.module("demo", []);

app.factory("MySvc", function() {
  var data = {};
  data.setData = function(key, value) {
    this[key] = value;
  }
  data.getData = function(key, def) {
    return key in this ? this[key] : def;
  };
  return data;
});

app.controller("test1", ["$scope", "MySvc", "$timeout",
  function($scope, MySvc, $timeout) {
    $timeout(100).then(function() {
      MySvc.setData("foo", "bar");
      $scope.data = MySvc.getData("foo");
    });
  }
]);

app.controller("test2", ["$scope", "MySvc", "$timeout",
  function($scope, MySvc, $timeout) {
    $timeout(500).then(function() {
      $scope.data = MySvc.getData("foo", "baz");
    });
  }
]);

app.controller("test3", ["$scope", "MySvc",
  function($scope, MySvc) {
    $scope.data = MySvc.getData("foo", "asdf");
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js "></script>

<div ng-app="demo">
  <pre ng-controller="test1">Test 1: {{ data }}</pre>
  <pre ng-controller="test2">Test 2: {{ data }}</pre>
  <pre ng-controller="test3">Test 3: {{ data }}</pre>
</div>

Answer №3

After tackling the issue head-on, I managed to solve it. Initially, I was using the following code snippet for redirecting to the new page:

$window.location.assign('/cards/service');

However, I decided to switch to this alternative code:

$location.path('/cards/service');

And voilà, it's now functioning as intended.

An interesting observation is that previously, when the redirection wasn't working, the console in the Chrome inspector would refresh with each reload. Now, with the new code, the console remains stable. Could anyone enlighten me on the distinctions between these two functions?

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

What is the most strategic way to conceal this overlay element?

Currently, the website I'm developing features a series of navigation elements at the top such as "Products" and "Company." Upon hovering over the Products link, an overlay displays a list of products with clickable links. Positioned at the top of the ...

How to deactivate a text box within a form that is dynamically generated using Angular

I have encountered an issue with disabling the textbox inside my dynamic form in AngularJS after clicking a button. My code works perfectly fine for disabling textboxes outside the dynamic form, but when I try to target the ID of the textbox within the dyn ...

Is there a way for me to display the image name at the bottom before uploading it, and have a new div created every time I upload an image?

Is there a way to display the image name at the bottom and have it create a new div every time an image is uploaded? I would appreciate any help with this... <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstra ...

Selection of Dropdown results in PDF not loading

I am facing an issue with my function that selects a PDF from a dropdown list. Instead of loading and displaying the PDF, it only shows a blank modal. Any suggestions on how to fix this? <li> <a href="">Case Studies</a> <ul clas ...

What is the reason behind the non-exportation of actions in Redux Toolkit for ReactJS?

Currently, I am utilizing @reduxjs/toolkit along with reactjs to create a shopping cart feature. However, I am encountering an issue when attempting to export actions from Cart.js and import them into other files like cart.jsx and header.jsx. The error mes ...

access the passport variable within the ng-view

Hello, I am encountering a slight issue. Here is the structure of my template: <div id="navbar">..... Connected as #{user.username} </div> <div id="main> <div id="ng-view"> Here go my partial templates </div> </div> ...

What is the best way to store selected items from a multi-select box in AngularJS that is generated using ng-repeat?

I have a scenario where I need to handle a group of select boxes instead of just one. Each select box holds a different option, and when the user changes their selection, I want to save that value in a variable or an array. I've managed to do this for ...

What method can I use to modify the object's keys based on certain conditions in ES6/React?

How can I dynamically change the value of an object's keys based on specific conditions? What is the most effective way to structure and implement this logic? Data const newData = { id: 111, name: "ewfwef", description: "Hello&qu ...

vuejs mounted: Unable to assign a value to an undefined variable

When I try to run the function below upon mounted, I encounter an error: "Cannot set the property 'days' of undefined" Here is my code snippet: function getDays(date) { this.days = (new Date()).getTime() / ...

Is it possible to pass a variable to a text constant in Angular?

In my constant file, I keep track of all global values. Here is the content of the file: module.exports = { PORT: process.env.PORT || 4000, SERVER: "http://localhost:4200", FAIL_RESULT: "NOK", SUCCESSFUL_RESULT: "OK ...

Are Yarn, Lerna, and Angular Libs causing issues with publishing?

Hey there! So, here's the situation - we are working with a monorepo setup using Lerna and Yarn, along with multiple Angular Libraries. In each package.json file for our libraries, you'll find something like this: "prepublishOnly": "yarn build ...

Retrieving information from PHP using AJAX

As a newcomer to the world of AJAX, I am faced with the task of retrieving data from a PHP file and storing it in a JavaScript variable. Despite exploring several examples, I have not been able to find a satisfactory solution. Here is a simplified HTML cod ...

Retrieving data from Node.js within an Angular application

I am currently working on retrieving data from MongoDB and displaying it on my website. However, I am facing an issue in sending the entire fetched object to a specific port (the response) so that I can retrieve it from Angular. I also need to know how to ...

Is there a way to activate a function in a sibling component without using Prop Drilling?

Looking at the image, you can see the structure of components I have. <Invoice> <Left></Left> <Right></Right> </Invoice> In the Left component, there is a form, and in the Right component, there is a Submit button l ...

The impressive Mean.io framework integrated with the powerful socket.io technology

Looking for guidance on integrating socket.io in the Mean.io stack? I've noticed that Mean.io frequently changes their folder structure, so I'm wondering where the best place is to configure socket.io. Should I use express.io instead? I'm ...

How can I ensure that each callback is passed a distinct UUID?

I am utilizing a package called multer-s3-transform to modify the incoming image before uploading it to my bucket. Below is the code snippet of how I am implementing this: const singleImageUploadJpg = multer({ storage: multerS3({ s3: s3, bucket: ...

Is it feasible to capture a screenshot of a URL by using html2canvas?

Is it possible to take a screenshot of a specific URL using html2canvas? For example, if I have the following URLs: mydomain.com/home mydomain.com/home?id=2 mydomain.com/home/2 How can I capture and display the screenshot image on another page? window ...

Unable to retrieve /ID from querystring using Express and nodeJS

I am brand new to the world of Express and nodeJS. I have been experimenting with query strings and dynamic web pages, but I keep getting an error saying that it cannot retrieve the ID. I'm completely lost as to where I might have made a mistake. An ...

The functionality to disable and reenable a button after performing a calculation is not functioning properly in the code

Here's the issue I'm facing with my code: When I click the search button, a for loop prints "hi" 5000 times. Before this loop starts, I want to disable the button. However, after the console.log is done, the button should be enabled again. But fo ...

Designing a dropdown menu within displaytag

I am currently utilizing displaytag to present tabular data, but I aspire to design a user interface akin to "kayak.com" where clicking on a row reveals additional details without refreshing the page. Here is an example scenario before clicking the Detail ...