What is the reason behind Angular's refusal to automatically bind data when an object is cloned from another object?

Check out this simple jsfiddle I made to demonstrate my question:

fiddle

Here is the HTML code snippet:

<div ng-controller="MyCtrl">   
    <div ng-repeat="p in products">
        <span ng-click="overwrite(p)">{{ p.id }}: {{ p.name }}</span>
    </div>
</div>

And here is the JavaScript code snippet:

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

function MyCtrl($scope) {

    var products = [{id:1, name:'first'}, {id:2, name:'second'}];
    $scope.products = products;

    var prod = {id: 3, name:'third'};

    $scope.overwrite = function(p){
        p.id = 4;
        p.name = 'forth';

        p = prod; // This does not work, nor does angular.copy(prod)
    }
}

After setting properties manually, they are bind correctly. However, when overwriting an object, nothing happens. Why is this? And how can I restore an object to its original state?

Let's say I create a backup object using

var productBackup = angular.copy(product)
. Then I make changes to the original product and later decide to cancel those changes by using product = productBackup. But unfortunately, this method doesn't work! Do I really need to manually reset all the properties like this?

product.id = productBackup.id;
product.name = productBackup.name;
etc...

Answer №1

To achieve the desired effect, utilize

angular.copy(source, destination)
.

check out the updated fiddle

The reason for this behavior is that angular continues to monitor the original p reference even after being assigned. By using angular.copy(), you can transfer the values from prod to p while still being accurately monitored by angular.

I previously inquired about a related issue which focused on a shared service.

Answer №2

While I lack experience with AngularJS, my understanding is that the issue lies in the fact that your parameter p is not a simple key/value object but rather a more intricate AngularJS object. When you assign your prod to it, you end up overriding the entire object instead of modifying specific parts.

You may find the following code snippet useful:

for(var key in prod) {
    p[key] = prod[key];
}

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 there a way to selectively add elements to the Promise.all() array based on certain conditions?

Here is the code snippet that I have written: I am aware that using the 'await' keyword inside a for-loop is not recommended. const booksNotBackedUp: number[] = []; for (let i = 0; i < usersBooks.length; i += 1) { const files = await ...

How can I clear a text box in Angular.js when the Google Autocomplete event is triggered?

Seeking assistance in AngularJS to clear the textbox value upon triggering the google map autocomplete event. Can anyone provide guidance? Here is the HTML code - <input ng-model="deployText" id="search_execute" class="form-control" type="text" place ...

Troubleshooting async/await issues in certain IDEs

I've been experimenting with aysnc and await in my project. While it worked perfectly in FiddleJS, I encountered an error when trying to implement it in my IDE (PHPSTORM 2017): async function test(url){ ^^^^^^^^ SyntaxError: Unexpected token f ...

Utilize focusout and onclick events on multiple components at the same time

Currently, I am in the process of coding an Autocomplete feature from scratch in Vue, but I am encountering a challenge when it comes to selecting an option from the dropdown menu. I have set it up so that the dropdown is shown when the input is clicked ...

Object displaying no visible illumination

Recently, I've been experimenting with this project, and after some trial and error, I've managed to get things working to some extent. As a novice in JavaScript, I'm unsure if the issue I'm facing has a simple solution. The problem is ...

What methods can I use to retrieve traversed objects using riak-js?

Utilizing Node with riak-js to interact with a Riak database. I have established two buckets named invites and events. The invites bucket contains a link to events. Is there a way to fetch both the invite object and the corresponding event object in one qu ...

JavaScript code for downloading data through AJAX and then loading a chart is not functioning as expected

<script> var highchartsOptions = { chart: { backgroundColor: 'rgba(255, 255, 255, 0.1)', type: 'column' }, title: { text: '' }, exporting: ...

Surprising results when a class is applied using jQuery

Exploring the differences between two fiddles (make sure to run the code on the jsfiddle pages to see the differences clearly). First Fiddle Simple demonstration: $("body").addClass("noScroll"); alert($("body").hasClass("noScroll")); $("body").removeCla ...

Tips for automating file uploads in HTML

I am having trouble filling the <input type="file"> element programmatically when trying to upload a file using a form. Can someone please provide me with guidance on how to accomplish this task? The method does not matter, I just want to achieve m ...

Preventing Event Propagation in JQuery Across Different Web Browsers

My GUI controls have a complex nested structure, and I need to prevent events from propagating up the DOM tree when they are clicked or changed. This functionality must be consistent across all browsers. Currently, I am using some cumbersome JavaScript co ...

A Beginner's Guide to Duplicating Bootstrap Containers in Jade

I am working with JSON data that is being transmitted from an Express and Mongoose Stack to be displayed on the user interface created in Jade. I am wondering which Jade Construct I should use to loop through a Bootstrap Container of col-md-4 using Jade s ...

Issue with Navigation Scrolling Feature on Wordpress

I am in the process of implementing a 'scroll-nav' for my website. To achieve this, I decided to separate the Navigation into two sections and incorporate some jQuery: <nav class="main-nav clearfix"> <?php wp_nav_menu(array('th ...

The Protractor option is nowhere to be found on the Run Configuration popup window in Eclipse

Issue with Protractor in Eclipse: Unable to locate Protractor option on Run Configuration popup. Despite following the steps outlined in http://www.protractortest.org/#/ and this guide on configuring Protractor with Eclipse (specifically the 2 Answer step ...

Sending HTML content to viewChild in Angular 5

I'm struggling to figure out how to pass HTML to a ViewChild in order for it to be added to its own component's HTML. I've been searching for a solution with no luck so far. As a newcomer to Angular, many of the explanations I find online ar ...

Is it possible to share a Vue.js component by "transferring" it rather than duplicating it?

In my comment system project using Vue.js, I have over 300 comments to manage. Each comment has an admin section that appears when the cursor hovers over it. Duplicating the admin section component for each comment is not ideal as it creates unnecessary l ...

Guide on utilizing the eval() function to assign a value to a field passed as a parameter

I am interested in achieving the following: function modifyField(fieldName){ eval(fieldName) = 1234; } In simpler terms, I want to pass a specific field name as a parameter and then assign a value to that field. Can someone guide me on how to accomp ...

What is the best way to eliminate the [lang tag] from a URL in Next.js?

I am looking to eliminate either the /en or the /it from the URL without explicitly adding it. i18next seems to be doing it automatically, and I am unsure how to disable this behavior. I simply want it to happen in the background. https://i.stack.imgur.co ...

The process of retrieving a comprehensive list of all event listeners in JavaScript or jQuery

When clicking on a particular link, I have a list of links that use AJAX to retrieve the appropriate file. For example, let's say I have files a.php and b.php in the "pages" folder. Clicking on the first link retrieves all the data from a.php, while c ...

AngularJS - Click event failing to trigger controller function

I am currently honing my skills in Angularjs and Nodejs through working on a project. Following a helpful tutorial, I have structured my folders and configured my routes. Issue: I implemented a method called isActive to update ng-class when a tab is ...

Make sure the inputs in separate table data cells are lined up in

I need help aligning two input fields in separate td elements to be on the same line. The issue I am encountering is that when an input is added to a td, it covers up any text within the td. https://i.stack.imgur.com/c7GiQ.png There are two scenarios: I ...