When altering a single scope variable in AngularJS, the effect cascades to impact other scope variables as well

After uploading my code on fiddle, I noticed that changes made to the myAppObjects variable also affect another variable. Here is the link to the code:
https://jsfiddle.net/owze1rcj/ Here is the HTML part of the code:

<div ng-controller="MyCtrl">
    <table>
    <tr ng-repeat="appObj in myAppObjects">
        <td>{{appObj.id}}
            <input type="checkbox" ng-model="appObj.cb1"></td>
        <td><input type="checkbox" ng-model="appObj.cb2"></td>
        <td><input type="checkbox" ng-model="appObj.cb3"></td>
        <td><input type="checkbox" ng-model="appObj.cb4"></td>
        <td><input type="checkbox" ng-model="appObj.cb5"></td>
    </tr>
    </table>
    <pre>
   first {{myAppObjects | json}}
    second {{AppObjects | json}}
    </pre>

</div>

This is the Controller part:

function MyCtrl($scope) {
    var a =[
        {
        id: 1,
        cb1: true,
        cb2: false,
        cb3: true,
        cb4: true,
        cb5: false
        }];

    $scope.myAppObjects = a;
    $scope.AppObjects = a;


}

Answer №1

Understanding the Differences Between Deep Copy and Shallow Copy

Diving into Shallow Copy

Shallow copy involves the top level object pointing to the same object.

Therefore, simply duplicating a single scope variable results in a shallow copy.

$scope.firstVar = $scope.secondVar;

In this scenario, both firstVar and secondVar are interlinked.

Delving into Deep Copy

Deep copy entails copying all objects within the copied object at every level, with each pointing to a distinct object.

angular.copy Generates a deep copy of the source, which must be an object or array.

$scope.firstVar = angular.copy($scope.secondVar);

In contrast, firstVar and secondVar here represent two separate entities.

Answer №2

function MyCtrl($scope) {
var myArray =[
    {
    id: 1,
    cb1: true,
    cb2: false,
    cb3: true,
    cb4: true,
    cb5: false
    }];

$scope.myAppItems = angular.copy(myArray);
$scope.AppItems = angular.copy(myArray);
}

Remember to utilize the angular.copy() method when assigning values to avoid copying variable references.

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

Managing a promise and using async/await functions

Having an issue with my node and express function router.post('/', async (req, res) => { const playlist = new Playlist({ song: req.body.song, artist: req.body.artist }) try { const newPlaylist = await play ...

Error encountered on NodeJS server

Today marks my third day of delving into the world of Angular. I've come across a section that covers making ajax calls, but I've hit a roadblock where a tutorial instructed me to run server.js. I have successfully installed both nodejs and expre ...

Storing data collected from a Google form into an Excel spreadsheet

I have created a form using table layout. My goal is to automatically shift the focus to the next input field once the current one reaches its maximum length. I tried implementing this functionality with jQuery, but it only seems to work with inputs and no ...

Do you think there is a more efficient way to solve this issue?

const [active, setActive] = React.useState(["active", "", "", "", ""]);``your unique text`` const hrefs = React.useMemo( () => ["/", "/about", "/skills", "/projects", "/contact"], [] ); React.useEffect(() => { setInterval(() => { ...

Can you explain the distinction between bodyparser.urlencoded and bodyparser.json?

I'm a bit confused about the use of bodyparser. Why is it necessary when we can simply use json.stringify (to convert an object to a string) and json.parse (to convert JSON to an object)? Is it because by using app.use() with bodyparser, the middlewa ...

Having trouble receiving a response when making a request to an API

I encountered an issue while trying to fetch an API. Initially, I received an error message stating that the message port was closed before a response was received. After removing all extensions, the error disappeared but now I am still unable to receive a ...

What is the best way to reveal the square's id value upon hovering over it exclusively?

In this assignment, I am refraining from using HTML and focusing on JavaScript to create functionality. Here's my progress so far: document.addEventListener("DOMContentLoaded", function () { let button = document.createElement('button' ...

The collection-repeat feature in Ionic seems to be having trouble displaying in the specified location

I have successfully developed an application, but I am facing difficulties in displaying a collection-repeat feature. Other functionalities within the app are working perfectly fine. ShowDetails.html <ion-view view-title="Parts Listing"> <ion ...

After cloning the variable from props, the Vue 3 Composition API variable becomes undefined

I have a main component containing code and tables, including a modal that is displayed based on a boolean value. The main component features the following modal: <ConfirmPaymentModal ref="confirmPaymentModal" :invoice="markAsPa ...

Tips for making an appended element match the height of an image

After embedding the div .soonOverlay into specific .smallCatalogBlock's, I am facing difficulty in adjusting the height of soonOverlay to match only the height of the img within smallCatalogBlock. Currently, its height extends throughout the entire co ...

Dynamically showing a div using JavaScript and AJAX after changing the window location

After successfully fetching data from the server through AJAX, I am redirecting to the same screen/URL. Is it possible to show/display a div after redirecting using jQuery? $.ajax({ type: "POST", url: action, data: form_data, success: func ...

Creating a render function that includes the img.src parameter requires careful thought and consideration

I am currently working on a dilemma where I need to dynamically adjust the height and width of an image in my render() function every time there is a state change. Here is the code snippet: render() { const imageURL = photos[this.state.currentImage]. ...

Dynamic routes in NextJS automatically append a .txt extension to the end of the URL

Issue: When using NextJS, the link <Link href="/link">link</Link> redirects to /link.txt For a simple link like this, HTML <a href="/link">link</a> can be used instead The real problem arises when using NextJS ...

Guide to launching a web browser within a Phonegap app with a button click event

We are developing a PhoneGap application using HTML and JavaScript. Our goal is to integrate PayPal's website so that users can make payments with a simple button click event within the app, and then seamlessly return back to the application afterward ...

JavaScript - If you change the properties of an object within an array, does it automatically set the array as needing an update?

If we were to imagine a scenario where there is an array containing 3 objects, and then I decide to access the second object by its index in order to modify one or more of its properties, what would happen? Would this modification mark the entire array a ...

Eliminating an element from an array without the need for iteration

I've been reviewing some documentation, but I have a hunch that there may be a simpler way to eliminate one element from an array without having to utilize an iteration loop. http://jsfiddle.net/G97bt/1/ Check out the updated jsFiddle example: http: ...

The Katura video is loading properly, yet it is rotating instead of playing

I am working on a web application that involves playing videos from Kaltura platform and then loading the link on an iOS webview. <html> <body> <div id="myEmbedTarget" style="width:400px;height:330px;"></div> ...

What is the best way to retrieve information utilizing Http.get within my project?

I have a TypeScript file containing user data: File path: quickstart-muster/app/mock/user.mock.ts import {User} from "../user"; export const USERS:User[]=[ new User(....); ]; I have a service set up at: quickstart-muster/app/services/user.service.ts ...

The magic of data binding in AngularJS's ng-repeat

Is it possible to dynamically call an attribute of a data-binded object based on the ng-repeat object? I have set up a simple example, but I'm not sure if it can be solved this way. Can anyone help with this? The goal is for the input to receive the ...

When subscribed to, the BehaviorSubject will return the object twice

When working with a bank API for payments, the response expected by the banks is that Ban Pay JavaScript will perform an HTTP redirect in the top frame to a completeUrl. The question arises - what should be the completeUrl that I need to provide to the ban ...