Is AngularJS known for its ability to bind variables across different components effortlessly

In the beginning of my Angular controller, I use Promises to download JSON data and then store it in variables:

app.controller('mainController', ['$scope', '$http', '$q', function($scope, $http, $q) {
  var req1 = $http({method: 'GET', url: 'link to JSON 1', cache: 'true'});
  var req2 = $http({method: 'GET', url: 'link to JSON 2', cache: 'true'});

  $q.all([req1, req2]).then(function(response){
    var res1 = response[0].data;
    var res2 = response[1].data;

    $scope.data1 = res1;       // Manipulated JSON
    $scope.data1Ref = res1;   // Reference JSON

    $scope.data2 = res2;
    $scope.data2Ref = res2;

    init(); // Process the data
  });
}]);

However, after init() is executed, both $scope.data1 and $scope.data1Ref seem to be bound together, leading to modifications in one affecting the other.

I am wondering why this happens and how can I keep a separate stored version of the original downloaded JSON for reference?

Answer №1

The reason for this behavior in JavaScript is that objects are passed by reference. When you assign res1 to $scope.data1 and $scope.data1Ref, you are actually assigning a reference to res1.

To solve this issue, you can create a deep copy of your res object by using the angular.copy method.

$scope.res1Ref = angular.copy(res1);

Answer №2

When assigning objects in your code, remember that you are simply giving the variable a reference to the object rather than creating a new copy of the object itself. This means that multiple variables can point to the same object instance. If you want to create a new object, you need to actually copy the existing one.

In Angular, there are two handy functions for copying objects: one for making a shallow copy and another for creating a deep copy. A shallow copy only duplicates primitive fields, while any child objects within the copied object will still reference the same instances as the original object. On the other hand, a deep copy creates entirely new copies of any child objects as well.

To perform a shallow copy, you can use angular.extend, while angular.copy is designed for deep copying.

Answer №3

When working with AngularJS, remember that complex objects are passed by reference. To learn more about this concept, check out the following link: Understanding the distinction between angular.copy() and assignment (=)

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

initiate a click event within another click event

This is an HTML Code snippet: <ul id="linkjess"> <li><a href="javascript:setfolder('medewerkers', '1000');">medewerkers 1000</a></li> <li><a href="javascript:setfolder('medewerkers', ...

Using JQuery's appendTo method with a lengthy string of elements that includes a mix of single and double quotes: a step-by-step guide

My content script is fetching data from the server in the form of an array of objects. The structure looks something like this: [ { "lang": "English", "videos": [ { "embed": "<iframe width='100%' height='421px&apo ...

Creating Seamless, Unified Shape-to-Shape (Containers) Transition with CSS and JavaScript - A Step-by-Step Guide

I am experimenting with creating a unique effect where two rectangular shapes, each containing text and with rounded ends, move towards each other, merge to form a single rounded rectangle as the page is scrolled down, and then separate back when scrolling ...

The method item.appendChild does not exist as a function

Despite being a common error, I've researched extensively and still can't figure out why it's happening. It seems like it should be an easy fix, but I'm struggling to find the solution on my own. var item = document.createElement("div" ...

Creating a dynamic list filter using JavaScript and three select boxes

Looking for a way to implement a similar feature to the one on this webpage: I will be showcasing a list of brands on the page, with each brand requiring three pieces of information: Starting letter Store (multiple options) Category (multiple options) ...

change the css back to its original state when a key is pressed

Is there a way to retrieve the original CSS of an element that changes on hover without rewriting it all? Below is my code: $(document).keydown(function(e) { if (e.keyCode == 27) { $(NBSmegamenu).css('display', 'none');} ...

Using setTimeout with drag and drop functionality in HTML

I need a setTimeout function to be triggered only after dragging and dropping an image into a division, not before the drop occurs. ...

Show the Canvas element at the back of the DIV

This particular question requires a clear explanation. My goal is to have the canvas act as a background element on the page, while the main content of the page starts in its usual position. I attempted using separate DIVs with their own Z-index values, bu ...

Ensure that the page has completely loaded using WebdriverJS

Is there a reliable method to ensure that a page has fully loaded using selenium-webdriver in JavaScript? I came across this similar query, but I require an implementation specifically in JavaScript. var webdriver = require('selenium-webdriver') ...

Command handler that dynamically utilizes both shared and separate commands

Currently, I am in the process of setting up a command handler for multiple channels on Twitch. To organize the commands, I have them divided into specific folders for each user and generic ones. Accessing these commands is done by using a map(). My goal i ...

When dynamically loading content with ajax, dynamic content fails to function properly

Currently, I am attempting to incorporate dynamic content loading after the user logs in by utilizing $.ajax. Here is how it's being done: $.ajax({ url: "functions.php", type: "GET", data: login_info, datatype: 'html', a ...

Display two images consecutively within a single img tag

My goal is to display two images using a single <img /> tag. The first small image will be loaded and shown using the src attribute, while the second large image will be contained within the data-src attribute. Only one image will be displayed at a t ...

An error occurred while trying to load the resource in the Redux-Saga: connection refused

Utilizing axios allows me to make calls to the backend server, while redux-saga helps in managing side effects from the server seamlessly. import {call, put, takeEvery} from "redux-saga/effects"; import {REQUEST_FAILED, REQUEST_SUCCESS, ROOT_URL, SUBMIT_U ...

What is the best way to modify directives in response to updates in services?

In my directive (parent-directive), I have a slider called mySlider. When the slider is stopped, it triggers an event that calls an Angular $resource service with two parameters. The service then returns an object. The structure of the directives is as fo ...

Exploring the possibilities of socket.io-client in combination with Vite.js and Vue for seamless real

I am currently diving into socket.io for my upcoming Vue project, but I seem to be encountering some issues. Interestingly, everything works smoothly when I use vue-cli, however, I prefer working with Vite.js due to its speed and customization options. Unf ...

Ways to attribute a numeric worth to a choice in a JavaScript form

I am in the process of creating a form that allows users to customize and order pizza while showing them the invoice as they make their selections. Currently, I have successfully implemented the display of user-selected options, but I am struggling with a ...

Deleting a database row when the cancel button is pressed

I have a scenario where I need to remove a database row containing a file name when the user clicks on the cancel button. However, despite my efforts, the database row is not being deleted. Can anyone help me identify what I might be doing wrong? Here is ...

Utilizing React Material-Table to Trigger a React Component through Table Actions

I have set up a datatable using the code below. <MaterialTable icons={tableIcons} title={title} columns={columns} data={data} actions={[ { icon: () => <Edit />, t ...

Which is more efficient: filtering a JSON object or querying the database using ajax?

I am currently developing a product page that involves a selection of options that will impact the pricing of the items. The primary option allows users to choose a material, which then influences the available set of options. Within the database, there i ...

Learn the best practices for sharing .env values from the main project component to various reusable npm installed components

In recent projects I've worked on using React and Vue.js, I have utilized .env variables to store API URLs for micro services and other configuration settings that are used throughout the root project. However, when it comes to child components insta ...