Updating a property in an object within an Angular service and accessing it in a different controller

I am currently utilizing a service to transfer variables between two controllers. However, I am encountering difficulties in modifying the value of an object property. My goal is to update this value in the first controller and then access the new value in the second controller. Please see below for my attempt.

You can check out the JSfiddle here

HTML code

<div ng-app="myApp">
    <div ng-controller="myController">
        <h3>{{objectValue.data}}</h3>
        <button ng-click="changeObject()">Change the objectValue</button>
    </div>

    <div ng-controller="myController2">
        <h2>{{ newValue.data}}</h2>
    </div>
</div>

JS code

var app = angular.module('myApp', []);

app.service('sharedProperties', function() {
    var objectValue = {
        data: 'default service value'
    };

    return {
        getObject: function() {
            return objectValue;
        }
    }
});


app.controller('myController', function($scope, sharedProperties) {
    $scope.objectValue = sharedProperties.getObject();

    var changeObject = function() {
      sharedProperties.objectValue.data = "New value";
    }
});

app.controller('myController2', function($scope, sharedProperties) {
    $scope.newValue = sharedProperties.getObject();
});

Answer №1

Within the initial controller of the demonstration, you are only assigning a single property from an object to a scope variable, essentially turning it into a primitive. Primitives do not support inheritance and are assigned by value

If you retain a reference to the same object within each scope model and simply display its properties in the view, the binding is maintained through object inheritance.

The primitive that is used for stringvalue in the demo service will not have any inheritance since it is not an object

By utilizing:

app.controller('myController1', function($scope, $timeout, sharedProperties) {

    $scope.objectValue = sharedProperties.getObject();    
});

And updating the view with:

{{objectValue.data}}

You will receive real-time updates in the view thanks to internal angular watches on the object

VIEW DEMO

Answer №2

The reason for this behavior is that strings are passed by value and not reference, so any changes made will not be reflected elsewhere. To fix this issue,

Replace

<li>{{objectValue}}</li>
with
<li>{{objectValue.data}}</li>

and

Update

sharedProperties.getObject().data
to sharedProperties.getObject().

This should ensure proper object binding.

If you also need to share strings, consider accessing them using getter functions in your controllers by modifying

$scope.stringValue = sharedProperties.getString();
to
$scope.getString = sharedProperties.getString;

and

Change

<li>{{stringValue}}</li>
to
<li>{{getString()}}</li>

For more information, refer to: http://jsfiddle.net/kbu1ts51/5/

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

JavaScript: Retrieving the names of children within a <div> element

Within my structure setup, there is a tower div with inner elements like this: <div class="tower"> <div class="E0">abc</div> <div class="GU">123</di </div> The challenge I am facing is that I need to access the in ...

Embed a website in an iframe and modify a portion of the URL within the embedded page

Welcome to my first question here! I am looking for a solution that will allow me to load a webpage inside an iframe while modifying parts of the URLs in any links on the page with different text. For example, let's say we load a website like "myweb ...

Delete the hidden attribute from an HTML element using a JavaScript function

Hey there! I have a question for you. Can you assist me in removing an attribute (Hidden) using an Input type button? Here is the script: Thank you for your help! <input type="button" onclick="myfunction()" value="Test"> <hr> <button id= ...

Can you please explain to me how to target a specific element by its ID in the DOM and then move on to the next element with the same ID using jQuery

During the event handling process, a scenario arises where two div elements end up having identical IDs within the DOM structure. While using JQuery, my objective is to specifically target the second occurrence of the div with the aforementioned ID in the ...

Exploring the importance of defining a JSONP callback function

I am relatively new to JavaScript and struggling with an issue in my code. My code includes an Ajax request to a server, and I receive a response from it. Due to the cross-domain nature of the request, I am utilizing JSONP. $.ajax({ url: "***", c ...

How to identify a request timeout when using $http in Angular?

I have a question about how to manage timeouts when making an http request using Angular. Here is the code snippet: $http({ url: url, params: params, method:'POST', headers: { 'Content-Type': 'application/x ...

Flow the child process output as it streams

I have a unique custom command line tool implemented in Python which uses the "print" statement to display its output. To interact with this tool from Node.js, I spawn a child process and send commands to it using the child.stdin.write method. Below is an ...

Do only the imported functions in a React App contribute to the overall size and overhead for the user?

For instance, my React application relies on the MUI package. However, I am only utilizing the Slider and AutoComplete components from the package. Do only these 2 components impact the performance of my application for the end user? Or does the entire p ...

Unable to retrieve the status for the specified ID through the use of AJAX

When I click the button in my app, I want to see the order status. However, currently all statuses are being displayed in the first order row. PHP: <?php $query = mysqli_query($conn, "SELECT o.orderid,o.product,o.ddate,o.pdate,k.kalibariname,o.sta ...

Utilize React and Django to showcase encoded video frames in your application

Having recently ventured into the world of web development, I've been facing a challenging problem that I can't seem to crack. My tech stack involves the use of React and Django. The issue at hand is with a 3rd party application that utilizes op ...

Is it possible to utilize $.each() in combination with $.ajax() to query an API?

I am dealing with an array containing 2 values, and for each value, I need to make an AJAX query to an API to check the stock availability. If there is stock for both values, a certain message should be executed, otherwise, a different message. This check ...

GeoJson with timestamp and marked directional indicator

I am looking to create an animation of a boat traveling along a specific route. Currently, I am able to display the route as a line and the boat as a circle using TimestampedGeoJson: # circle with following line features = [ { 'type': ...

Searching for the position of different size values according to their specific value

information = { boxNoTo: 1, boxNoFrom: 1, size: 'M', } items = [{ size: 'M', },{ size: 'M', },{ size: 'S,M,L,XS', boxNoTo: 1, boxNoFrom: 1, country: 'CA', name: 'Josh' }] This is what I have don ...

Displaying dates in Material UI datepicker is not working

My current setup involves using Material UI v14.4 with React, and I have encountered an issue with the DatePicker component not displaying the dates correctly as shown in the attached screenshot. Strangely, there are no visible error messages either. Any s ...

Error encountered: The initMap function from the React Google Maps API is not recognized. No relevant

Encountering an issue where initMap is not recognized as a function. I attempted to avoid utilizing any additional packages for asynchronously loading the script or Google Maps API. My initial approach was to simply console log initMap to track when the sc ...

Error in React Material UI: 'theme' variable is not defined - no-undef

In the process of developing a basic React application with material-ui, I am incorporating MuiThemeProvider and ThemeProvider for themes. App.js import React from 'react'; import { createMuiTheme, MuiThemeProvider } from '@material-ui/co ...

Notification continuously appears when clicking outside of Chrome

I have implemented the use of onblur on a text box to display an alert. However, I encountered an issue where if I click outside my Chrome browser after entering text in the text box and then click on the Chrome browser button in the task bar, the alert ap ...

Deactivating the idle timer in React Native: A Step-by-Step Guide

Currently, I am working on an app that involves a timer using RN. However, I have noticed that after approximately 1 minute and 50 seconds, the device's screen starts to dim in preparation for sleep mode. ...

Transform a global JavaScript function into a global Vue.js function, compatible with the Vue Laravel framework

My JavaScript function displays a color border when required and changes the color if anything is inputted. It works fine in plain JavaScript but not in Vue. I need to use this function in Vue, on any place or component. app.js $('.req' ).on(&a ...

Tricks for refreshing cached web page assets in the year 2023

So far, here are some of the old Cache Buster techniques I've come across: Adding a query string in the link src: /mstylesheet.css?cache_buster=12345 Changing the filename each time: /mstylesheet-12345.css Using Apache with Cache-Control "must-revali ...