The array's value fluctuates into a negative without any direct manipulation from my end

In order to work with the $scope.option value, I stored it in a temporary variable and then applied operations on the temporary variable after changing all the values of $scope.option to negative numbers.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  
  $scope.options=[1,2,3];
  
  var tmp = $scope.options; 
  
  for(var i=0;i<tmp.length;i++){
    tmp[i] = tmp[i]*-1;
  }
  
  console.log($scope.options);
  
  document.getElementById("p1").innerHTML = $scope.options;
   
   
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<p id="p1"></p>

</div>
</body>
</html>

Answer №1

Instead of simply copying the values using var tmp = $scope.options;, opt for angular.copy() instead.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  
  $scope.options=[1,2,3];
  
  var tmp = angular.copy($scope.options); 
  
  for(var i=0;i<tmp.length;i++){
    tmp[i] = tmp[i]*-1;
  }
  
  console.log($scope.options);
   
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<p ng-repeat="option in options">{{ option }}</p>

</div>
</body>
</html>

Answer №2

Employ the angular.copy(); method to duplicate your object/array into a new temporary array

Answer №3

When working with arrays in JavaScript, assigning an array to a variable does not create a new copy of it - the variable simply refers to the same array object. This means that any changes made to the array through one variable will also affect the original array.

In simpler terms, both the variables tmp and $scope.options point to the exact same array.

To create a separate copy of the array referenced by $scope.options and assign it to tmp, you can use the slice() method like this:

var tmp = $scope.options.slice();

The slice() method essentially duplicates the array and provides a reference to the duplicated array. With this approach, you can modify elements within tmp without affecting the contents of $scope.options.

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

Determining the height of a Bootstrap column in relation to another element

Utilizing the grid layout from bootstrap, I have the following structure: <div id="prof_cont_enclose"> <div class="row"> <div class="prof_cont_row"> <div class="col-xs-12 col-sm-4 col-md-2 col-lg-2 prof_elem"&g ...

How should I proceed if I encounter an npm error stating that cb() was never called?

Hey everyone. I keep encountering an issue with npm whenever I attempt to install packages. I am receiving the following error message: npm ERR! cb() never called! npm ERR! This is an error with npm itself. Please report this error at: npm ERR! <h ...

When utilizing the `express.static(__dirname)` function in Node.js with Express, the visitor may be directed to an incorrect HTML page

My website consists of a login page named login.html and an index page named index.html. I want to implement authentication so that only logged in users can access the index page. I have not set up the post method on the login HTML page. Therefore, I have ...

Highcharts Maps - Circular zoom controls

Currently implementing the Highcharts API for a special project. All features are functioning well except for one issue. I am looking to make the zoom in/out buttons appear rounded. I have attempted using border-radius with 50%, as well as modifying the r ...

Can you tell me the JavaScript alternative to Jquery's .load() shortcut method?

Exploring the modernized version of jquery, specifically the .load() ajax shorthand method that is not deprecated. One example to consider is finding the javascript equivalent for the traditional jquery ajax shorthand method mentioned below: $("#targetdi ...

Guide to iterating through a JSON object

Initially, I expected a simple question but it's proving to be more challenging than I thought. To provide some context, there is a JSON string returned from the server located within data.occupation. {"occupation": "Boxer", "id": 2},{"occupation": " ...

Issue with React-Toastify not displaying on the screen

After updating from React-Toastify version 7.0.3 to 9.0.3, I encountered an issue where notifications are not rendering at all. Here are the steps I followed: yarn add [email protected] Modified Notification file import React from "react" ...

Sending information to a personalized mat-grid element using properties

I am currently working on enhancing the functionality of the angular material mat-tree component by building a custom component. The main objective is to create a table with expandable and collapsible rows in a hierarchical structure. I have managed to ach ...

Guide on excluding a specific element using an Xpath expression

I am seeking a solution to craft an XPath expression that can target all <p> elements except for p[6] and p[7]. Currently, I have formulated this expression: //div[@class="Job-Description app-responsive-jd"]/p[1], which is functioning corre ...

Is PHP loaded prior to the `html body`?

I'm facing a unique challenge where I am currently transferring variables from a PHP page to hidden HTML inputs. The values are extracted from these hidden inputs using a JavaScript function that is called in the following manner: <body onload=" ...

Tips for adding an array to an array of objects with AngularJs

I'm facing an issue with the array structure in my code. Here's what I currently have: $scope.arrayList=[{FirstName:"",LastName:""}]; $scope.Address=[{address:"",PhoneNumber:""}]; What I want to achieve is to push the $scope.Address array into ...

Ways to add the class "active" to the initial element in a Vue.js for loop

I am currently diving into learning vue.js and am working on adding a list of elements. My goal is to apply the class="active" only to the first element in the for loop. Below is the snippet of my code: <div class="carousel-inner text-center " role="li ...

I am facing issues with the sorting functionality in a Kendo grid that is locally bound and using AngularJS

When using the AngularJs Kendo grid to bind local data array from a service request, I encountered an issue with sorting. The grid sorts correctly initially, but when new data is appended to the array, the sort functionality stops working. I tested this be ...

My confidential environment variables are being inadvertently revealed to the client by Next.js

I am encountering a problem with my project in which an environment variable is being revealed to the browser. Despite the documentation stating that only environment variables prefixed with NEXT_PUBLIC_ should be accessible in the browser environment, all ...

What strategies can be implemented to effectively utilize both client-side and server-side validation without redundant efforts?

Currently, I am validating user input on the server side using PHP. However, the client side sends XMLHttpRequest calls and highlights invalid fields with red borders. While this method works well, I believe it can be time-consuming for users to wait for a ...

Placing an image on a three.js cube using overlay does not function properly

I attempted to superimpose an image onto a cube by utilizing code from GPT chat and Blackbox AI, but in both cases, I encountered a black screen. I saved the code in a file named test.html and tested it on Google Chrome and Opera GX browsers, only to be me ...

What is the best method for retrieving a child control from a TR element?

I am facing an issue with a hidden field inside each Tr in my template: <ItemTemplate> <tr style="" class="ui-selectee trClass ui-widget-content"> <td style="width: 100px"> <asp:HiddenField ID="idField" runat=" ...

Tips for bringing in and adding an excel spreadsheet to a kendo grid with the help of JQuery

I am facing a challenge with my kendo grid as I am trying to incorporate an excel file into it. Specifically, I would like to import and add an excel file to my kendo grid. If, for instance, my kendo grid initially has 3 rows, after importing an excel file ...

Choose the minimum price from the JSON response of the API

I have made an AJAX request to an API and received the following JSON response below. I am trying to extract the lowest 'MinPrice' from the 'Quotes' data but finding it challenging to determine the best approach. One method I am consid ...

Activate modifications in a distinct column?

I've been exploring a solution to achieve a similar functionality where clicking or hovering on headings in a column brings up corresponding text in another column. My idea is to use list items with a carousel for this purpose, but I'm facing so ...