AngularJS modifying shared factory object across controllers

Is it possible to update the scope variable pointing to a factory object after the factory object has been updated? In cases where there are 2 angular controllers sharing a factory object, a change made to the factory object by one controller does not reflect in the scope variable of the other controller.

Example: http://jsfiddle.net/zjm0mo10/ The expected result is "Factory foo.bar is 666" but it shows "Factory foo.bar is 555".
var app = angular.module('myApp', []);
app.factory('testFactory', function(){
return {
    foo: {bar:555},
}               
});

function HelloCtrl($scope, testFactory)
{
    $scope.bar = testFactory.foo.bar;
    $scope.clickme = function()
    {
        alert("testFactory.foo.bar "+testFactory.foo.bar);
        $scope.$apply();
    }
}

function GoodbyeCtrl($scope, testFactory)
{
    testFactory.foo.bar = 666;
}

<html>
<div ng-controller="HelloCtrl">
    <p>Factory foo.bar is {{bar}}</p>
    <button ng-click="clickme();">btn</button>
</div>
</html>

Answer №1

To ensure your scope properties are set correctly, you can assign testFactory.foo to $scope.foo. For example:

$scope.foo = testFactory.foo;

Next, in your code, make sure to reference the factory property using {{foo.bar}} to maintain the integrity of testFactory.foo.

Additionally, it is important to remember that you do not need to include $scope.$apply() in your clickme() function. The ng-click directive automatically triggers a digest cycle.

For a visual representation of these concepts, you can check out this example on JSFiddle.

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

Tips for dynamically updating data with on.click functions in D3

Implementing pack layout with D3 v4 is my current task, and I am looking to adjust the circle sizes based on the values "funds" and "spend" in my csv file. The following code successfully scales the circles: rank(funds) rank(spend) However, the on.click ...

Encountering a Zone.js error when trying to load an Angular 7 app using ng serve, preventing the application from loading

Scenario: Yesterday, I decided to upgrade my Angular app from version 5.2.9 to 6 and thought it would be a good idea to go all the way to 7 while I was at it. It ended up taking the whole day and required numerous changes to multiple files, mostly due to R ...

Encountering a TypeError with react-rte in Next.js: r.getEditorState is not a valid function

In my Next.js project, I am using a React RTE component. It is displaying correctly, but when I navigate to another component and then return using the browser's back button, I encounter the following error: Unhandled Runtime Error TypeError: r.getEd ...

NextJS does not support the rendering of the map function

Currently, I am getting acquainted with NextJS by creating a basic blog. I have successfully passed the data through props and can see it logged in the console within the map function. However, I am facing an issue where the HTML content does not display i ...

Unable to invoke setState (or forceUpdate) on a component that has been unmounted

After updating the component, I encountered an issue with fetching data from the server. It seems that componentWillUnmount is not helpful in my case since I don't need to destroy the component. Does anyone have a solution for this? And when should I ...

Loading indicator displayed at the top of a div using JavaScript/jQuery

My current challenge involves implementing a progress bar, similar to the pace.js progress bar. The issue arises when the browser is refreshed, as the pace.js progress bar loads on top of the body instead of within a specified div. It is important that the ...

Adjust the color of the input range slider using javascript

Is there a way to modify the color of my slider using <input type="range" id="input"> I attempted changing it with color, background-color, and bg-color but none seem to work... UPDATE: I am looking to alter it with javascript. Maybe something al ...

Unable to close window with window.close() method after initially opening it with JS or JQuery

I am currently using an Instagram API that requires users to log out through the link . This link redirects users to the Instagram page, but I want them to be redirected to my own page instead. Although I tried different methods from a previous post on thi ...

Performing an API GET request in a header.ejs file using Node.js

Looking to fetch data from an endpoint for a header.ejs file that will be displayed on all routed files ("/", "/news" "/dogs"). Below is my app.js code: // GET API REQUEST var url = 'https://url.tld/api/'; request(url, function (error, response, ...

jQuery offset(coords) behaves inconsistently when called multiple times

I am attempting to position a div using the jQuery offset() function. The goal is to have it placed at a fixed offset from another element within the DOM. This is taking place in a complex environment with nested divs. What's puzzling is that when I ...

Tips for embedding a script into an HTML document

I've been experimenting with tinymce npm and following their guide, but I've hit a roadblock. Including this line of code in the <head> of your HTML page is crucial: <script src="/path/to/tinymce.min.js"></script>. So, I place ...

What is the best way to specifically target and style a component with CSS in a React application?

I'm facing a small issue with the React modals from Bootstrap in my application. In index.html, I include the following: <link rel="stylesheet" href="/assets/css/bootstrap.min.css"> <link rel="stylesheet" href=& ...

After resolving a promise, what is the process for loading a Next.js App?

Seeking guidance on implementing the code snippet below using Next.js. I suspect there is an issue with Next.js not being able to access the window object without being within a useEffect(() => {}) hook. When switching back to regular React, the code ...

No traces of SOI could be detected in the stored canvas image

I have a unique project using Three.js, where I am enabling users to save diagrams they draw on a canvas as JPEG images. The process involves: <a id="download" download="PathPlanner.jpg">Download as image</a> function download() { var dt = ca ...

Express.js experienced a 404 error when processing POST requests

When working with js and express, the route handler file looks like this: var express = require('express'); var passport = require('passport'); var authRoutes = App.route('authRoutes'); va ...

The Mystery of Two Nearly Identical Functions: One function is queued using Queue.Jquery, but the effects fail to work on this particular function. What could be causing this

In short, I am currently working on my first portfolio where I am utilizing Jquery to manipulate text. My goal is to have the text fade in and out sequentially. However, when using the queue function to load another function, the text within the span tag ...

Revamping the hyperlinks in my collapsible menu extension

Is there a way to modify the links in this accordion drop menu so that they lead to external HTML pages instead of specific areas on the same page? I've tried various methods but can't seem to achieve it without affecting the styles. Currently, i ...

What is the process for creating the AngularJS documentation?

I find the documentation for AngularJS to be easily understandable - I wonder how it is created? If JSDoc is used, where can I find the style sheet? ...

Exploring the functionality of ISO 8601 periods with JavaScript

Has anyone successfully compared ISO 8601 periods in JavaScript to determine which period has a longer duration? For example, is P6M (6 months) longer than PT10M (10 minutes)? I haven't been able to find any built-in solutions for this. Any suggestio ...

What is the best way to retrieve app.state in a Remix project when running a Cypress test?

One way Cypress can expose an app's state to the test runner is by using the following approach in React: class MyComponent extends React.Component { constructor (props) { super(props) // only expose the app during E2E tests if (window.C ...