What could be the reason behind the alteration of a different variable within an AngularJS controller

I have a AngularJS controller set up as shown below:

schedule.controller('schedule', ['$scope', '$http', function($scope, $http){
    $http.get('/zt-api/business/admin/' + window.location.pathname.split('/')[2]).success(function(data){
        $scope.admin_times = data;
        $scope.admin_times_unix = data;
        $scope.weekDays = {'Saturday': "شنبه", 'Sunday': "یکشنبه", 'Monday': "دوشنبه", 'Tuesday': "سه شنبه",
            'Wednesday': "چهارشنبه", 'Thursday': "پنجشنبه", 'Friday': "جمعه"};
        angular.forEach($scope.admin_times, function (value, key) {
            angular.forEach(value, function (value2, key2) {
                angular.forEach(value2, function (value3, key3) {
                    angular.forEach(value3, function (value4, key4) {
                        angular.forEach(value4, function (value5, key5) {
                            var info = $scope.admin_times[key]["week_"+ key][key3].times[key5];
                            if (!isNaN(info)){
                                var myObj = $.parseJSON('{"date_created":"'+ $scope.admin_times[key]["week_"+ key][key3].times[key5] +'"}'),
                                myDate = new Date(1000*myObj.date_created);
                                $scope.admin_times[key]["week_"+ key][key3].times[key5] = myDate.toLocaleString().split(", ")[1]
                            }
                        });
                    });
                });
            });
        });
    });
}]);

I updated $scope.admin_times, but strangely, $scope.admin_times_unix is also getting updated. Why is this happening? Any suggestions on how to fix it?

Answer №1

When you assign the same reference of data to both admin_times and admin_times_unix, any changes made to one object will impact the other.

To avoid this issue, you can use angular.copy which creates a new reference instead of using the actual reference.

$scope.admin_times_unix = angular.copy(data);

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

Whenever I save innerHTML to a text file, a newline break is automatically inserted in the saved text file. The same newline break also appears when I reload the page

Whenever the button is clicked, the text file saves with a line break for every p tag inside div1, not just the first one. <p>x1</p> ....linebreak If the button is clicked three times, reloaded, and then clicked again, the result is as follows ...

"Implementing the functionality to handle checkbox click events and changes in Angular

Encountering an unusual issue with checkboxes in angular2 (beta 17). Attempting to align checkboxes with elements in an array and bind the change or click event. Here is an example array: myObjects=[ {value:true}, {value:true}, {value:false} ...

Accessing properties in JavaScript using square brackets

When I input the following code into my Chrome console: var object = {0:0, 1:1} I am able to retrieve the values by calling object[0] and object[1]. Surprisingly, even when I use object["0"] and object["1"], I still get the same results. Then, if I redef ...

The react boolean attribute is malfunctioning and the video is not playing automatically

I have a React component with a <video> element that includes the autoplay attribute. <video autoplay muted src="/vids/vid.mp4"> However, it does not work as expected. Interestingly, when I set autoplay="true", it starts wo ...

Storing multiple pieces of data within a single key in JSON is a convenient

Is there a way to store multiple values in a single key of a JSON object? For example: { "number" : "1","2","3", "alphabet" : "a", "b", "c" } I'm looking for something similar to this. Any suggestions or tips? ...

What is the method to stimulate a browser refresh using programming?

In my setup, I have three computers with specific roles - the Server, Client, and Viewer. As the administrator, I have control over both the server and the viewer devices. When a user from the Client machine connects to the Server, they are greeted with ...

Issue with Animation not functioning properly when InterstitialAd is displayed

Ever since I was in grade 7, I have been passionate about building games and apps. Although I learned some XML back then, I lost my ambition over the years due to life's distractions. However, two weeks ago, I decided to teach myself Java and created ...

Implementing toastr notification messages using Restangular and Angular UI-Router

Searching for a better solution to display error messages when restangular fails to load data. Using toastr for site-wide messaging, but injecting toastr dependency to app.config is not working. What is the recommended way to show toastr alerts for bad ht ...

What is causing the error "unable to access property 'map' of undefined" in my code?

Currently working on React + Redux and trying to implement a likes counter. However, encountering an error 'cannot read property 'map' of undefined'. Here is the code snippet for my Reducer: const initialState = { comments: [], ...

Issues with Implementing Scroll Directive in Angular JS

Apologies for asking what may seem like a silly question. I'm still new to using AngularJS and recently came across a neat little scroll directive on http://jsfiddle.net/88TzF/622/. However, when I tried implementing the code in the HTML snippet below ...

Combining duplicate values in MongoDB using aggregation

In my code, I have an aggregate function that counts the occurrences of a value in the database: let data: any = await this.dataModel.aggregate( [ { $match: { field: new ObjectID(fieldID), }, }, ...

Javascript handles the sorting of elements within an array

I have spent time searching for a solution to my issue, but so far, I have not been successful in finding one. My PHP array is arranged exactly as I need it to be, but when I attempt to display it using JavaScript, the order gets distorted, specifically w ...

Transitioning library functions to utilize promises

converter.json2csv(MAP.fls, function (error, csv) { if (error) { return error; } file_system.writeFile(MAP.output.res, csv, function (error) { if (error) { return error; } }); }); I am currently working ...

Sending JSON data two times to the ASP.NET MVC controller via POST request

function onTestComplete(content) { var url = '<%= Url.Action("JsonTest","Organization") %>'; $.post(url, null, function(data) { alert(data["name"]); alert(data["ee"]); }); } <% using (Ajax.BeginForm("JsonTe ...

Is there a way to integrate personalized Javascript files within Bootstrap 4?

As I work on developing my own components of Bootstrap 4 for a dashboard site, I have run into a challenge. I need to include custom JS to be compiled with my Bootstrap 4 project, but I am facing limitations. Every time I try to include a module, I am unab ...

Vue: Develop a master component capable of displaying a sub-component

Is there a way to design a main component that is able to accept and display a subcomponent? Take the following scenario for instance: <Container> <Item/> <Item/> <SubMenu/> <Btn/> </Container> ...

Using JavaScript to navigate options in an HTML select element

I've implemented jqtransform to customize the appearance of form selects. However, I am unable to navigate and select options using arrow keys. Is there a way to select options using keys? Any solutions? Below is my HTML code snippet: <form> & ...

How to find a collision between a spherical object and a triangular shape in a three

In my research, I am exploring the possibility of detecting collisions between a triangle and a sphere in three.js. Currently, I have devised a method using the raycaster and the sphere's vertices. However, this approach has proven to be unreliable a ...

Data is not appearing when using Node.js with mongoose and the populate() method

I am facing an issue while trying to display data from a database. Even though I have integrated 3 different schemas into one, the combined data is not being displayed as expected. I have attached all three schemas for reference. While async-await along w ...

Utilizing Spring JPA with JSON/JSONB Postgres columns for efficient data storage and

Despite searching for answers on this topic, I have not found a simple solution to my basic question. I am utilizing JPA CRUD Repository to store an entity. In my Postgres DB table, there is a column of type JSON and in my corresponding JPA Entity, the co ...