The reference to a $scope array in AngularJS has not been properly updated

Check out the code snippet below:

var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
$scope.people = [
    { id: 1, first: 'John', last: 'Rambo' },
    { id: 2, first: 'Rocky', last: 'Balboa' },
    { id: 3, first: 'John', last: 'Kimble' },
    { id: 4, first: 'Ben', last: 'Richards' }
];
$scope.updateByReference = function() {
  var tst = $scope.people;
  tst = [];
  console.log($scope.people);
}
});

The expectation was for the $scope.people to be an empty array object after running the updateByReference function, but it doesn't seem to be updating. You can test it out on this fiddle: http://jsfiddle.net/9fR23/409/

Answer №1

When you assign $scope.people to a variable like var tst = $scope.people;, you are actually copying the reference to the object, not its value. So when you modify tst by doing tst = [], you are only changing the reference stored in tst, not the original object referenced by $scope.people.

To properly reset the $scope.people variable, simply do:

$scope.people = [];

Answer №2

 let data = $scope.people;  //data points to $scope.people.

This means that any modification made to data or $scope.people will affect both variables.

RESOLUTION:

 $scope.updateByReference = function() {
      let data = JSON.parse(JSON.stringify($scope.people));
      data = [];
      console.log($scope.people);
    }

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 upload multiple files using JavaScript?

My JavaScript project can be found on GitHub. You can check out a live demo of the project here. The main goal for my HTML Button with id='Multiple-Files' is to enable users to upload multiple files, have them displayed in the console, and then ...

Is there a way to automatically input an array of elements into a form without having to do it manually

Is it possible to create a form using an array of items fetched from a database, and automatically populate the form with each of these elements? Currently, I'm facing difficulties as the form appears empty. What am I missing? Below is the code I ha ...

The top choice for AngularJS: A trustworthy JSON viewer and editor module

Currently, I am working on enhancing my app by incorporating a json editor feature. I would appreciate any recommendations on which module you have experience with and believe is both stable and effective. The data I am working with is already in json for ...

Troubleshooting the issue of CSS animations activating twice and causing a flickering effect specifically in the Firefox browser

I am facing an issue with CSS animations in Firefox. When I try to slide in some radio buttons upon clicking a button, the animation seems to be firing twice in Firefox while it works fine in Chrome. I have attempted several solutions but haven't been ...

Vue PWA - manifest.json replaced upon refreshing the page

I'm encountering an issue with my Progressive Web App (PWA) where reloading the page manually or redirecting using window.location results in the manifest.json file being overwritten with the contents of index.html. This leads to an error stating Mani ...

"Encountering an issue where ng-repeat doesn't reflect updates after adding a new value to the array. Attempted to use $scope.$

Whenever the chat is opened and a name is clicked, it triggers $scope.openChat(user) which adds a name to the $scope.chat.openChats array. The ng-repeat is supposed to monitor this array for any new values but does not update. I attempted using $scope.$app ...

Manipulating Angular and Typescript to utilize the method's parameter value as a JavaScript object's value

I am currently working with Ionic, Angular, and Typescript, attempting to dynamically set the value of a location based on the parameter passed from a method. Here is the relevant code snippet: async fileWrite(location) { try { const result = a ...

Utilizing Material UI Grid spacing in ReactJS

I'm encountering an issue with Material UI grid. Whenever I increase the spacing above 0, the Grid does not fit the screen properly and a bottom slider is visible, allowing me to move the page horizontally slightly. Here is the simplified code snippe ...

What is preventing the slider handle from being moved?

Having trouble getting the slider handle to move when testing it out. Could use some assistance on this matter. Included a Fiddle link for your reference. JavaScript Code: var current_plan = {}; var plans = [ { 'name' : 'Business&apo ...

Navigate to a different component within Angular

Is there a way in Angular to scroll to a component using a button placed in another component? Below is the code snippet for the first component: <div id='banner' class="col-5 offset-1 d-flex justify-content-center align-items-cen ...

Struggling to integrate the c3 chart library with Angular, encountering loading issues

I've been attempting to utilize the c3 angular charts, but unfortunately nothing is displaying on my page. Despite checking for console errors and following a tutorial, I still can't seem to get anything to show up. I have cloned the git repo an ...

AngularJS: utilizing the @ symbol to mention someone in a textarea field

Looking to create an autocomplete form that activates when the "@" symbol is typed in a textarea, similar to the functionality in this library: . I want to achieve this using only AngularJS and CSS. What type of directive would be best for this task? Addi ...

The div is unable to display data retrieved from the php file using Ajax

This is the function utilizing ajax $(document).ready(function() { $('#submit').click(function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: 'searchphp.php&apo ...

Converting Custom Data Arrays to JSON using JavaScript

My goal was to create a utility function that can convert custom data (the type of data Sencha Touch stores use) into JSON format. I've made progress, but the function fails when dealing with complex data from the Twitter API, although it works fine w ...

Troubleshooting difficulties integrating NodeJS with R using an R script

I have been attempting to execute an R-script from a js-file but I am consistently receiving a null value as the return. Here is my folder structure: -R_test --example.js --helloWorld.R The contents of example.js are as follows: var R = require(" ...

Using a javascript parameter in a cshtml file to filter data in a datatable

Here is the model code public class viewCase { public List<string> lstCategory { get; set; } public DataTable dtWrkTsk { get; set; } } This is the controller code string query = "SELECT WorkFlowID,Subject,Category FROM CMSTasksWorkFlow" ob ...

Ways to access the current element in the Evernote editor that corresponds to the cursor's position?

It seems that Evernote editor uses a Rich Text Editor which differs from the input or textarea tag. Therefore, I am unable to use the provided code to determine its type. Is there a way to retrieve the current element of the Evernote editor where the curso ...

Unable to retrieve valid inputs from text fields by utilizing jQuery selectors

Extracting information from text fields is my goal. Specifically, these fields contain dates which consist of three parts: the year, month, and day. The dates are divided into two sections - the first date and the last date, serving as boundaries for a sea ...

From Table to DIV: A Simple Conversion

I have encountered a major issue that has stumped me so far. Perhaps you can assist me. I am dealing with a table that appears as follows: __________________________________ | | time1 | time2 | time3 | +--------+-------+-------+-------+ | John | ...

Determining whether a user possesses a specific role

Currently, I am using mongoDb within my express server to store user information in the following structure: var UserSchema = new Schema({ username: { type: String, required: true, index: { unique: true } }, password: { type: String, required: ...