Reputation: 818
Am trying to assign scoped variable to a normal javascript variable in AngularJS script, and modifying the value of normal variable.. But I see that based on the change that is made in normal variable, Scoped variable data gets changed automatically.. How can we unchange the data of Scoped Variable even after modifying the normal javascript variable?
Am using a button in HTML code to invoke the assign()
I have below AngularJS code
<script>
var app = angular.module('ExampleApp', ['ui.plot']);
app.controller('PlotCtrl', function ($scope)
{
'use strict';
$scope.sname = "Tttt";
$scope.dataset_v = {
"d0": { "id": 0, "name": "Housing", "value": 18 },
"d1": { "id": 1, "name": "Travel", "value": 31.08 },
"d2": { "id": 2, "name": "Restaurant", "value": 64 },
"d3": { "id": 3, "name": "Bank", "value": 3 },
"d4": { "id": 4, "name": "Movies", "value": 10 }
};
$scope.assign = function ()
{
var dataset=$scope.dataset_v;
// Declare resulting empty array
var d = [];
// Get object keys and iterate over them
Object.keys(dataset).forEach(function (key)
{
// Get the value from the object
var value = dataset[key].value;
// Update values if in the range
if(value >= 10 && value <= 20) {
dataset[key].value = 7;
} else if(value > 20 && value <= 40) {
dataset[key].value = 8;
}
// Push the updated(or not) value in the array
d.push(dataset[key]);
});
alert(JSON.stringify(d, null, 4));
});
</script>
After making the change on normal js variable i.e., dataset and d..
$scope.dataset_v should not get changed, so it should be original only like below, how can we do that ?
$scope.dataset_v = {
"d0": { "id": 0, "name": "Housing", "value": 18 },
"d1": { "id": 1, "name": "Travel", "value": 31.08 },
"d2": { "id": 2, "name": "Restaurant", "value": 64 },
"d3": { "id": 3, "name": "Bank", "value": 3 },
"d4": { "id": 4, "name": "Movies", "value": 10 }
}
Am using normal javascript variable (dataset and d) for storing modified values to post them to server for datastore (Internally).
Upvotes: 1
Views: 58
Reputation: 19337
This :
var dataset=$scope.dataset_v;
Creates a new variable pinting towards the same array.
What you need is a new array. You should copy the entire array and modify the copy :
var dataset = angular.copy($scope.dataset_v);
angular.copy
performs a deep copy, unlike direct assignement or array.slice
wich creates a shallow copy (new array but same elements).
Upvotes: 2
Reputation: 85538
You could use angular.copy()
. Instead of
var dataset = $scope.dataset_v;
use
var dataset = angular.copy($scope.dataset_v);
By that you preserve the original dataset_v
.
Upvotes: 4