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

Discover the best correlation among multiple arrays

I am currently developing a chat script that allows users to specify their interests. Upon connecting to the server, the client sends a JSON payload over WebSocket containing information such as ID, hash, auto message, and interests. {"id": int, "hash": m ...

Angular JS displays an error message when the user selects an input field and fails to provide any input

On my wizard steps application, I have implemented Angular JS validation that displays errors when the user enters and removes a character in the input field. However, I am trying to figure out how to show the error message if the user tabs onto the fiel ...

The Best Approach for Angular Google Maps Integration

I'm diving into Angular for the first time while working on a project that requires advanced mapping functionality like clustering, routing, road routing, paths, directions, polygons, events, drawing on maps, info windows, markers, etc. After some re ...

Tips for monitoring input content "live"

Currently, I am in the process of developing a web form that includes a text field intended to receive numeric values. If the user enters non-numeric characters into this field, the form will not submit. However, there is no error message displayed to noti ...

What causes an array to accumulate duplicate objects when they are added in a loop?

I am currently developing a calendar application using ExpressJS and TypeScript. Within this project, I have implemented a function that manages recurring events and returns an array of events for a specific month upon request. let response: TEventResponse ...

Unexpected failure when using FormData in Ajax callback for large files

I have a file upload control where I can upload various types of files. After getting the file, I store it in a FormData object and make an ajax call to my controller. Everything works well with images and small .mp3 files. However, when I try to upload .m ...

Converting yard values to meter values using AngularJS: A comprehensive guide

My task is to convert meter values to yard using two dropdowns. The first dropdown contains various values, while the second dropdown has "meter" and "yard" options. If "meter" is selected in the second dropdown, the values in the first dropdown remain unc ...

Adjustable Scroll Bar

Could anyone help me find a component similar to the resizable scrollbar on Google Finance? Check out this link: http://www.google.com/finance?q=EURUSD&ei=bhM_UKDXF-aIWqAPVNQ You can see it below the chart. If you know where I can find something like ...

How can I transfer a selected value from a unique dropdown component to react-hook-form?

I am utilizing react-hook-form for form validation in this Gatsby project. However, my dropdown component is not a <select> tag but a customized component created with divs and an unordered list. This design choice was made to meet our specific custo ...

How can an Angular 2 component detect a change in the URL?

My Angular 2 component subscribes to a service based on the URL hash without calling any subcomponents. I am wondering if I should use Route or Location for this scenario, and how can I listen for and react to a pop state event? ...

Direct back to the current page post deleting entry from mongodb

After removing data from MongoDB, how can I redirect to the same view (handlebar)? I tried using res.render, but it shows that the website cannot be reached. Thank you for your assistance. Controller Logic var express = require('express'); va ...

How to add an OnClick listener to a cell element in a table built with the Tan

I am currently working on a project using React and trying to implement a table. I want to show an alert when a header cell in the table is clicked, displaying some information. However, I have been struggling to find assistance on adding a click listener ...

Resolving issues with JavaScript caused by Polymer updates

I am a novice when it comes to working with Polymer. From what I have gathered, there seems to be compatibility issues with Mozilla and Safari. After researching on StackOverflow, I found that adding addEventListener('WebComponentsReady', funct ...

Unable to assign a value to a property within an object using AngularJS

const objectData = {}; objectData[key]["digits"] = `${set.first},${set.second},${set.third},${set.fourth}`; When key is a numeric value, an error occurs: TypeError: Cannot set property 'digits' of undefined ...

Having trouble executing react-native project using the command "npx react-native run-android"

Hey there! I've been working on a react-native project for quite some time now and everything was going smoothly until yesterday. I encountered an error when running the command npx react-native run-android in Metro before the project had fully execut ...

Using ng-grid in conjunction with the "controller as" syntax

According to this GitHub issue, ng-grid may not support Angular's "controller as" syntax, but is there a way to still use it? Update: Check out the basic example from the ng-grid website: http://plnkr.co/edit/lBgeAf?p=preview var app = angular.mod ...

Node.js Request Encoding Using Google Translate

I have developed a node.js module to use the Google Translate API. module.exports = function(sourceText, sourceLang, targetLang, callback) { var qst = qs.stringify({ client: 'gtx', sl: sourceLang, tl: targetLang, ...

Having trouble with AngularJS - struggling to diagnose the issue

HTML Page <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="assets/js/angular.min.js"></script> ...

What are the steps to resolve an invalid token error when receiving it? (repl.it)

Today marks my introduction to node.js, recommended by a friend. Due to limited resources, I have opted to utilize repl.it for hosting. However, I am faced with an error in my first attempt at using it. The purpose of my current script is to make my user ...

Obtaining your CSGO inventory via Steam API using jsonp: A step-by-step guide

Hey there! I'm currently facing an issue while trying to access a player's CSGO inventory using Valve's API. Unfortunately, I keep running into the error message stating that no 'access-control-allow-origin' header is present on th ...