The Angular duplication method

Recently, I came across the following code snippet in an Angular tutorial...

<div ng-app="myApp" ng-controller="formCtrl">
  <form novalidate>
    First Name:<br>
    <input type="text" ng-model="user.firstName"><br>
    Last Name:<br>
    <input type="text" ng-model="user.lastName">
    <br><br>
    <button ng-click="reset()">RESET</button>
  </form>
  <p>form = {{user}}</p>
  <p>master = {{master}}</p>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.master = {firstName: "John", lastName: "Doe"};
    $scope.reset = function() {
        $scope.user = angular.copy($scope.master);
    };
    $scope.reset();
});
</script>

As for the line

$scope.user = angular.copy($scope.master);
, do you think it could have been simplified to $scope.user = $scope.master; since $scope.master is expected to remain constant and immutable in this scenario?

Answer №1

When utilizing the `=` operator in JavaScript with objects, you're simply assigning the reference rather than creating a new object (new reference). If you use `angular.copy`, it will generate a new object in this scenario.

In coding terms:

let obj1 = {}, let obj2 = {}
obj1 !== obj2; // true
obj1 = obj2;
obj1 === obj2; // true
obj1 = angular.clone(obj2);
obj1 !== obj2; // true

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

Is it possible to manipulate CSS on a webpage using javascript?

I have incorporated this piece of JavaScript to integrate a chat box onto my website: window.HFCHAT_CONFIG = { EMBED_TOKEN: "XXXXX", ACCESS_TOKEN: "XXXXX", HOST_URL: "https://happyfoxchat.com", ASSETS_URL: "https://XXXXX.cloudfront.ne ...

Generating output into several spans of identical class using JavaScript with compatibility for IE8

Trying to make sense of GetElementsbyClassName function here. My goal is to output the value of an input field, identified by ID, to multiple spans that share a common class on click. I had it working fine with ElementId, but now I need to repeat the user ...

Forcing ng-dirty in AngularJS form validation

When using AngularJS for form validation, I want all required fields to be marked as erroneous when the user clicks submit. To achieve this, I am utilizing input.ng-dirty.ng-invalid to style the controls with errors. My goal is to set ng-dirty on required ...

Looking to display a different HTML document in a div - any suggestions?

I am in the process of creating a website that will feature four tiles on the front page. Once a tile is clicked, I would like the content to appear in a window that has a slight transparency to allow the main page to show through. So far, I have managed ...

How can I fetch data from SQL using JavaScript based on a specific value in PHP?

My application is built using the Yii2 framework. Within my application, there is a view.php file that consists of an element and a button. The element, <div id="userId">, contains the user's login ID, and I aim to use the button to re ...

Using JavaScript to access and retrieve a key/value pair from a nested object

In my JavaScript code, I am attempting to extract the Category property as an array from a nested key/value object structure. Here is an example of the data: var data = [{key: "A", values:[{Category:"One", amount:2000}, {Category: "Two", amount:2500}, ...

Employ AngularJS to run an expression stored in a variable

How can I evaluate an expression stored in a variable? I am looking for a solution where a formula can dynamically change based on other inputs. For example, consider the following data: $scope.items = [{ name: 'first', formula: &ap ...

Creating a new item in Angular 2 using user input

Just dipping my toes into Angular2 and attempting to append a new item to the list through input. However, upon clicking submit, instead of text I get [object Object]. Check out the code snippet below: app.component.html <form (submit)="addItem(item) ...

Executing an onscroll function based on window.innerWidth in JavaScript

I want to trigger my scroller function only when the window width exceeds 599 pixels and the user is scrolling. The function itself works fine during scrolling, but adding an event listener seems to cause it not to work. Can anyone offer guidance on how ...

Creating links within a single image in HTML?

Is there a way to hyperlink different parts of a single image to various webpages using JavaScript coordinates or any other method? ...

Extract information from a specific div element and save it to a text file

I'm currently working on extracting data from a div and sending it to a PHP file using the following JavaScript: $(document).ready(function(){ $('#save').on('submit',function(e) { var bufferId = document.getElementById ...

Error encountered: Unable to access the 'showBarChart' property of an undefined variable within a React application

I am working on a function that customizes the tooltip for a scatter plot in nvd3. To update the state within this function, I am calling another function that utilizes setState: chart.tooltip.contentGenerator(function (d) { var html = "<div>" ...

Guidelines for Transmitting Form Data to Multiple PHP Files

I'm currently working on a Form within an HTML page that sends data to http://www.aaaaaa.com/1st-file.php. Here's an example of how the form is set up: <form action="http://www.aaaaaa.com/1st-file.php" method="post" enctype="plain" id="theFor ...

Issue with jQuery in Internet Explorer causing difficulties loading images

I'm experiencing an issue with my website where all the images load on top of each other when the site is first loaded, creating a chaotic mess. The desired functionality is for the images to remain invisible until specific words are clicked, which is ...

The absence of a semicolon in the non-null assertion is causing an

Within my code, I have a function that arranges a set of cards according to a specific coordinate system: const orderCardsInPage = (items: OrderItemType[], pageCards: CardType[]) => { return pageCards.sort((firstCard, secondCard) => { con ...

Having trouble with dynamic CSS styles not functioning properly in Internet Explorer?

My issue involves dynamic CSS settings not functioning properly on Internet Explorer: Here is the code snippet causing the problem: <div class="i-storage-bar-chart-bar-container"> <div class="i-storage-bar-chart-bar" ...

Changing the value of HTML elements from Node.js is not allowed

I am facing a challenge with an HTML form that requires user input. Once the form is completed, the data entered needs to be validated to ensure that the username provided is unique. If the username is not unique, I need to reload the sign-up page (signUp. ...

Returning to two ancestors with jQuery

Hello everyone, I'm attempting to locate the following tag: <tr class="grid-layout-row"> within this block of HTML: <tr class="grid-layout-row"> <td role="presentation" class="grid-layout-row-leader"> <div class="gr ...

Retrieving Data from Outside Source using AngularJS

Is there a way to retrieve JSON-Text-Stream data from a specific URL (e.g. SOMEURL/ean.php?id=4001513007704)? The returned result typically appears as follows: { "product": { "ean_id": "4001513007704", "title": "Gerolsteiner Mineralw ...

Displaying the fields of the selected [object Object] in the console.log

Currently, I am utilizing "express": "3.2.6",, nodeJS v0.10.25, and "express-myconnection": "1.0.4",. The database connection appears to be functioning properly. However, when attempting to query in my view: console.log("Data: " + rows); The output rece ...