Sharing data between AngularJS controllers only functions properly on the initial attempt

I have been working on sharing data between controllers in AngularJS using a factory, but I am facing an issue. Despite following solutions from similar questions, I can only get it to work the first time around. In my app, there are 3 different states, with one of them being a simple calculator. My goal is to display the total from the calculator state in a separate state as well. However, with the current code, the total always shows up as 0, indicating that it only works initially and does not update when the 'total' value changes. Any suggestions on how to resolve this?

HTML:

<div class="list card">
  <div class="item item-divider">Total</div>
  <div class="item item-body">
    <div ng-model="figure">
      <b>{{figure}}</b> calories consumed today
    </div>
  </div>
</div> 

'home' controller:

.controller('homeCtrl', function($scope, total) {

$scope.figure = total.get();

})

Calculator Controller:

.controller('calcCtrl', function($scope, total) {

$scope.result = 0;

$scope.reset = function() {
    $scope.result = 0;

};

$scope.add = function(i) {
    if(!i){

    }else {
        $scope.result = $scope.result + parseInt(i);
        total.set($scope.result);

    }
};

});

Factory

.factory('total', function() {

var val = 0;

return {
get: function() {
    return val;
},
set: function(num) {
    val = parseInt(num);
    }
};  
})

Answer №1

To enhance performance, consider using an object for storing the value(s).

var store = {value : 0};
return {
  get: function() {
    return store;
  },
  set: function(number) {
    store.value = parseInt(number);
  }
};  

Alternatively, always utilize the get() method to retrieve the most up-to-date value.

.controller('homeCtrl', function($scope, total) {
   $scope.number = total.get;
})

Then in the HTML:

<b>{{number()}}</b>

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

Displaying information on a chartJS by connecting to an API using axios in VueJS

Struggling with inputting data into a ChartJS line-chart instance. The chart only displays one point with the right data but an incorrect label (named 'label'): Check out the plot image The odd thing is, the extracted arrays appear to be accura ...

The Benefits of Semantic Class Names compared to Microdata

As I strive to use semantic class names, my exploration of microdata and SEO raises a question: Is it necessary to use both? Compare these two HTML snippets representing an event: Using CSS classes: <div class="event" itemscope itemtype="http://schema ...

Suggestions for changing sub-component data in Vue

I have a scenario where I am using a component with tabs inside. The Head component (parent) includes the following code: <v-btn @click="setSelectedTab('Set') "> ... <component :is="selectedTab"></component> ...

A guide on utilizing the intl.formatRelativeTime() function effectively

I need to display messages like "created 1 hour ago" or "created 1 day ago," as well as in plural form, such as "created 10 minutes ago" or "created 3 days ago." To achieve this, I am attempting to utilize the FormatJS API, specifically the intl.formatRela ...

Is there a way to execute a JavaScript file within another JavaScript file?

I'm in the process of developing a text-based game through the console, utilizing an NPM package known as "prompts" to prompt the user for input. One specific question it asks is, "What OS do you want to run?" and returns the selection as JSON data. F ...

selecting arrays within arrays according to their date values

With an array of 273 arrays, each containing data about a regular season NFL football game, I am looking to categorize the games by week. In total, there are 17 weeks in the NFL season that I want to represent using separate arrays. The format of my array ...

Showing the number of times a button has been pressed

I have written some HTML code to create a button and now I am looking for guidance on how I can use Vue.js to track how many times the button has been clicked. Here is what I have so far: <div class="123"> <button id = "Abutton&q ...

Develop an ngDialog template that can be easily reused across different projects

I am interested in developing a reusable template for my application. As far as I know, it seems like you can't directly pass the title and body to ngDialog. What I'm looking for is something similar to the following : <div> <h2>{{ ...

Utilize a random file import with the help of React JS, Babel, and ES6

Having trouble displaying a random image using webpack. I have a directory with various images, such as: 1.jpg, 1-cropped.jpg 2.jpg, 2-cropped.jpg I want to fetch a random image from this directory without manually adding a reference for each file. I&apo ...

Searching and filtering through various objects using AngularJS ng-repeat

I have two array objects called user and test. I am using the ng-repeat directive on the test object along with a search filter, but it seems to only work for the test object and not the user object. Here is my code: <label>Search</label> & ...

Struggling to retrieve JSON object sent to PHP using POST

I apologize if this question has already been asked. I have searched for a solution but nothing has worked for me yet. I am attempting to send a large JSON object to a PHP file using the POST method. Below is my JavaScript code : var grid = { ...

Limiting access to all routes except one

Lately, I've been exploring the combination of ExpressJS + AngularJS and encountered a bit of a tricky situation. My objective is to create a single login page and a dashboard page. By using Passport + MongoDB for user authentication, my plan is to v ...

Automatic Form Saving in Angular 4

Seeking to create a form data autosave feature in Angular 4. The functionality should operate as follows: User modifies data in the form -> save request sent to DB. A timer is initiated for 2 seconds. During the 2-second window after the previous s ...

What is the process of linking an alert message to the controller?

Hey everyone, I've been playing around with a simple commenting app built with AngularJS and I'm facing a challenge in displaying an alert message when a user enters an empty string into the input field. Below is the HTML view with ng-show logic ...

What steps should be taken to refresh an Expo app block once new data is retrieved from the database

I'm facing an issue with connecting my expo app to a database. I have utilized react redux to fetch data from the database, and upon successful retrieval of data, I aim to update my furniture block with the obtained information. However, despite recei ...

Unable to store/upload array of objects in Parse backend

My attempt to integrate an array into the parse.com backend hit a roadblock. I started by creating an array: var addHoles = function () { $scope.holeArray = []; for (var i = 0; i < 18; i++) { $scope.holeArray[i] = { number ...

How can background wait for executescript in a Chrome Extension?

I'm currently encountering an issue while developing my first Google Chrome Extension. In my background.js script, I have a scenario where I call script.js every second. Here's a simplified version of the code: script.js: /* Some code */ if (co ...

Gather data from various HTML elements with JavaScript when submitting a form

How can I extract values from HTML elements and send them for processing through a form? I'm attempting to compile a menu item list with the individual items' structure in place, but I'm struggling to figure out how to fetch the values upon ...

Implementing dynamic CSS in AngularJS using conditional statements

One technique I've been using in angularjs involves toggling between two windows using the ng-click and ng-show directives: <div ng-init="showTab2 = false"> <a ng-click="showTab2 = true; showTab1 = false ">#Tab1 </a> ...

Place the simulation nodes in designated locations

Is there a proper way to position nodes at specific coordinates using simulation force in D3.js? I am trying to place nodes at specific positions with forceX/Y simulation in D3.js. My understanding is that setting the strength to 0 should result in no for ...