AngularJS variable insertion to another is not copying value - javascript

I have an interesting problem.
App.controller('ABCController', function() {
$scope.valueA = 'abcd';
var tmp = $scope.valueA;
/* Do some actions with tmp */
tmp = tmp.replace('a', 'bc');
tmp = tmp.split('b');
...
console.log(tmp);
console.log($scope.valueA);
}
The result of console.log is showing updated tmp, but also, $scope.valueA is updated, too, which is same as tmp.
This is not what I expected. In the "var tmp = $scope.valueA" clause, angular provides the pointer of $scope.valueA? Did you face this problem before?

Try this
var tmp = value;
reportList.push({tag : 'abcd',ticker :'bcde',published : true, key:value);

You can use var tmp = angular.copy(value);
In your case both tmp and value are pointing to the same location in memory. So any changes in tmp will result in a change in value. Both tmp and value holds the same instance and any update or change will be reflected on both variables.

Related

Split php varibale with JS into array

I have tried everything and I can not split a PHP variable into two parts so I can insert them into two input fields. I have read numerous topics here and I don't see the problem...
This peace of code gives me a result that php variable is inserted into a wanted filed.
Lets say the PHP variable is data1-data2:
document.hiderad.selectstate.onchange = updateText;
function updateText() {
var str = document.hiderad.selectstate;
document.hiderad.opis.value = str.value;
}
Code above inserted data1-data2 into wanted HTML input.
And soon as i try to split it i get undefined warning. I have tried 7 different things to approach this problem so i want even list all the versions I tried. Can someone please help?
document.hiderad.selectstate.onchange = updateText;
function updateText() {
var str = document.hiderad.selectstate;
var array = str.toString().split('-');
a = array[0], b = array[1];
document.hiderad.opis.value = a.value;
document.hiderad.iznos.value = b.value;
}
Code above gives me b undefined if i remove last line i get a undefined.
You shouldn't be using a.value and b.value, that's for getting the value of an input field, not a string. You should use that to get the value of the selectstate input.
Also, always declare local variables unless you have a specific reason to assign global variables.
function updateText() {
var str = document.hiderad.selectstate;
var array = str.value.split('-');
var a = array[0], b = array[1];
document.hiderad.opis.value = a;
document.hiderad.iznos.value = b;
}

Using a variable increment to create new variables in Javascript

It might be a beginner's question, but I can't seem to find an answer on this.
The data it is getting is data out of a JSon file. I want it to loop through all the rows it is seeing. The loop works how it is written below and returns me the info I need with the rest of the code. I am trying to create multiple variables like testVar1, testVar2, testVar3, .... I don't know if it is possible to do it this way, or if I need to find another solution.
var i = 0;
for (var x in data) {
var testVar1 = data[0][1]; // works
var testVar[i] = data[0][1]; // doesn't
i += 1;
}
How can I make the testVar[i] work ?
What is the correct syntax for this?
Your code misses the initialization of your array variable: var testVar = [];.
⋅
⋅
⋅
Anyway, you may want to create those variables in the window object :
for (var i = 0; i <= 2; i++) {
name = 'var' + i;
window[name] = "value: " + i;
}
console.log(var0);
console.log(var1);
console.log(var2);
That way you can keep using the "short" variable name.
You can wrap all those variables in an object.
instead of:
var testVar1 = data[0][1];
Try:
var Wrapper = {};
//inside the for loop:
Wrapper["testVar" + i] = data[0][i];
...and so on.
You'd access them as Wrapper.testVar1 or Wrapper["testVar" + 1].
The problem you're having is pretty simple. You try to declare a variable as an array and in the same statement try to assign assign a value to a certain index. The reason this doesn't work is because the array needs to be defined explicitly first.
var testVar[i] = data[0][1];
Should be replaced with:
var testVar = []; // outside the loop
testVar[i] = data[0][1]; // inside the loop
Resulting in:
var i = 0,
testVar = [],
data = [
['foo', 'bar', 'baz'],
['kaas', 'is', 'baas']
];
for (var x in data) {
var testVar1 = data[0][1];
testVar[i] = data[0][1];
i += 1;
}
console.log('testVar1', testVar1);
console.log('testVar', testVar);
console.log('testVar[0]', testVar[0]);
console.log('testVar[1]', testVar[1]);
If i isn't an integer you should use an object instead. This can be seen in the answer of Tilepaper, although I advise against the use variables starting with a capital letter since they suggest a constant or a class.

What does this[var_name] = 12; do in JavaScript

Today I've seen code on w3resource and I was thinking what it does:
var var_name = 'abcd';
var n = 120;
this[var_name] = n;
console.log(this[var_name]);
// the OUTPUT : 120
// This line was added to this example.
console.log(abcd);
Firstly I thought it's to change the variable value but when I type var_name in the console to get the value it gave me 'abcd'. Actually this is very confusing to me.
In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. But since in the code the this is used globally it relates to the document level. So,
var var_name = 'abcd';
Creates a variable name var_name with value abcd. This is commonly used to create a variable.
But,
var n = 120;
this[var_name] = n;
Can be accessed when you make an object. We add properties to this when we want the properties to exist with the life of the object. We Use var for local variables.
Hence, this[var_name] and var_name are treated separately.
Hey I've added comments to the lines. Hope this helps you to understand the code
var var_name = 'abcd'; //creates a new variable with the name var_name and the
value 'abcd'
var n = 120; //creates a new variable with the name n and the value 120
this[var_name] = n; //add a new property with the value of var_name (abcd) to this and the value of n (120)

Push values to array in jquery

I have List of items data and empty array quotations :
var data = {};
var quotations = [];
I want to fill quotations with data values ,Every time i add new data it added successfully but all data values get last value .
for example :
$("#addquotation").click(function () {
debugger;
var itemname = $("#itemname").val();
var cost =parseFloat( $("#cost").val());
var notes = $("#notes").val();
var date = $("#date").val();
data.Item = itemname;
data.Cost = cost;
data.Notes = notes;
data.Date = date;
quotations.push(data);
)};
for first time i add
"test,45,testnotes,2016-02-03" Second time i 've added
"test2,45.2,testnotes2,2016-02-05"
when i debug i get data as :
obj(0): "test2,45.2,testnotes2,2016-02-05"
obj(1):"test2,45.2,testnotes2,2016-02-05"
it seems it append last version to all data
Please Advice . Thanks
You need to declare data inside the click handler, if it's declared as a global variable you are basically always modifying and adding the same data object to the array:
var quotations = [];
$("#addquotation").click(function () {
debugger;
var data = {};
var itemname = $("#itemname").val();
var cost =parseFloat( $("#cost").val());
var notes = $("#notes").val();
var date = $("#date").val();
data.Item = itemname;
data.Cost = cost;
data.Notes = notes;
data.Date = date;
quotations.push(data);
)};
You are pushing the same object reference each time since you declared data outside of the click handler.
Change from :
var data={};
$("#addquotation").click(function () {
To
$("#addquotation").click(function () {
var data={};// declare local variable
The problem is that data is a global variable and you add a reference to data to quotations.
When the first value is pushed to quotations, data and quotations[0] refer to the same object. Here is an example of what is happening:
var a = {num: 1};
var b = a;
b.num = 2;
console.log(a.num); // prints 2
The same thing happens when an object is pushed to an array. quotations does not contain a copy of data, it contains a reference to data so that modifying data also modifies quotations. To fix this, each element of quotations must refer to a different data object. This can be accomplished by defining data inside of the function instead of outside.
Replace
var data = {};
$("#addquotation").click(function() {
// populate data, push to quotations
});
with
$("#addquotation").click(function() {
var data = {};
// populate data, push to quotations
});

Why this json swap code does not work?

I have this fun :
swapjson = function (j1,j2)
{ var jj = JSON.parse(JSON.stringify(j1));
j1 = JSON.parse(JSON.stringify(j2));
j2 = jj;
}
I have also:
var myjson1 = {'x':1000, 'y':1000};
var myjson2 = {'x':2000, 'y':-2000};
swapjson (myjson1,myjson2);
console.log myjson1.x
1000 ?????
And I discover that inside the swapjson function the swap is made but not after call.
What is happen ? I dont understand what I'm doing bad...
Any help would be appreciated.
You can't replace the entire object like that, as the object itself isn't passed by referenced.
You can however change properties of the object passed, and it will stick, as a copy of the object is passed in.
So instead of parsing to strings and back to objects you can just iterate over the two objects keys, and replace one by one
swapjson = function (j1, j2) {
var temp = {};
for (key in j1) {
temp[key] = j1[key];
delete(j1[key]);
}
for (key in j2) {
j1[key] = j2[key];
delete(j2[key]);
}
for (key in temp) {
j2[key] = temp[key];
}
}
FIDDLE
You copy the value of myjson1 (which is a reference to an object and nothing to do with JSON) into j1, and the value of myjson2 into j2.
Then you overwrite the value of j1 and the value of j2.
You never change the values of myjson1 or myjson2.

Categories

Resources