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 best way to customize the appearance of Image tags located inside SVGs, whether they are in separate files or embedded within the code

I am developing a custom SVG editor application and facing an issue with implementing a highlighted effect when an <image> element is clicked. I have successfully accomplished this for other elements like <circle> by adjusting attributes such a ...

Get an MP4 on your iPhone (iOS) by downloading it from a link on a webpage

Despite trying various methods such as the HTML5 download tag, JavaScript, JQuery, and other techniques, I have not been able to successfully download a file to the Album. While photos can be saved by long clicking and selecting "Save Image", videos do n ...

The filter functionality is not functioning properly in AngularJS

Currently, I am working on an AngularJS extension and encountering an issue with the filter functionality. In the popup page of my extension, there is a button. Upon clicking this button, the ancestor node of the button gets blocked, and its relevant info ...

Is there a way to use JavaScript to alter the existing URL?

Currently, I am utilizing a select tag to allow users to choose the number of 'rows' displayed on the table. <%=select_tag :per_page, options_for_select([10,20,50,100]....some more code...., onchange => "if (this.value) {windows.location=& ...

Can you explain the distinction between Array() and [] in Javascript, and when would it be preferable to use one over the other?

Similar Question: Understanding the difference between "new Array()" and "[]" in JavaScript array declaration When working with JavaScript, you have the option to create a new array using: var arr = new Array(); or simply using: var arr2 = []; Wha ...

Tips for storing data in local storage for multiple users using AngularJS 1

service.setState = function (sessionObj, user) { $localStorage.sessions[user] = { sessionObj: sessionObj, user: user }; } service.getState = function (user) { return $localStorage.sessions[user]; } I have implemented this cod ...

Eliminating an element from an array without the need for iteration

I've been reviewing some documentation, but I have a hunch that there may be a simpler way to eliminate one element from an array without having to utilize an iteration loop. http://jsfiddle.net/G97bt/1/ Check out the updated jsFiddle example: http: ...

What is the process for extracting the time value from a jQuery timepicker?

I have been attempting to retrieve values from my time picker when a selection is made, but I am not seeing any values returned nor displayed in my HTML timepicker input field. Despite trying various methods, none have proven successful thus far. Method ...

JavaScript Class Reference Error

Questioning the mysterious reference error in the JS class from MDN page. The structure of the Bad class's constructor leaves me baffled – is it because the empty constructor calls super() as a default? class Base {} class Good extends Base {} cla ...

Traversing an array of objects using D3.js

I'm attempting to create a row of bars that are all the same height and width based on their titles. I have an array of 100 objects, each with a key called results containing another array of 20 objects. This means I should end up with a row of 2000 b ...

Content moves as you scroll, not within a lightbox

I have implemented lightbox style overlays for my 'Read More' content on my website. However, I am facing an issue where the content within the lightbox does not scroll; instead, the background page scrolls. Any assistance with resolving this p ...

Encountering the error message "This expression cannot be invoked" within a Typescript React Application

I'm working on separating the logic from the layout component in my Typescript React Application, but I suspect there's an issue with the return type of my controller function. I attempted to define a type to specify the return type, but TypeScr ...

Using Jquery and the cookie.split method to extract and eliminate a value from a cookie

I am trying to figure out how to remove a specific matching value from a cookie using JavaScript. I have written a script that loops over the cookie and checks for matches, but I can't seem to successfully remove just the matching value. Any tips on a ...

"Is it possible to selectively load only a few images on a website that contains numerous

My website displays numerous images hosted on a server. Each page contains a maximum of 100 images, each within its own div element. At any given moment, only one div is visible due to the CSS "display" property, while the others are hidden using display:n ...

Retrieve information from a JSON file and dynamically showcase it within a REACT component

Hey there! I'm a newbie in the world of programming and currently working on creating a carousel using Bootstrap and React. My aim is to make the Carousel images dynamic by fetching data from a local .json file. However, my current implementation seem ...

Receiving no communication from Express Router

Having trouble receiving a response from the server after making get/post requests. I've tried adjusting the order of functions in index.js without success. I also attempted to send a post request using Postman to localhost:8080/register, but the requ ...

Insufficient module names remaining in NPM

Starting to release modules on NPM has been on my mind, but I can't help but worry about the limited availability of sensible module names in the public domain. Is there a way to create a public NPM module that organizes all my module names within a ...

How can you efficiently pass multiple JSON files as arguments for Observable Arrays, especially when the values from one file are required for use in another file?

My goal is to utilize $.getJSON to retrieve data from two JSON files and assign their values to observableArrays. Currently, I have hard-coded the JSON data into the observableArray. You can view an example on this JSFiddle link. This was my initial appro ...

Having trouble with the functionality of a simple jQuery toggle menu on mobile?

I am experiencing an issue with a simple toggle menu that utilizes jQuery's on: tap feature, but it is not functioning as expected: <nav id="mobile-nav"> <ul> <li>Item 1</li> <li>Item 2</li> ...

Select2.js Dropdown List with Case Sensitivity

Currently making use of select2.js version 4.0.3 Situation: Imagine the dropdown list contains the following options: JavaScript javascript Javascript javaScript So, when a user types in java, all options are displayed (case is n ...