why two $scopes updates at the same time, duplicate data - javascript

I have this piece of code
$scope.addToOrder = function(index) {
var tempItem = $scope.item;
if (tempItem[index].validate == true){
if (_.isEmpty($scope.item2) == true) {
$scope.item2.push(tempItem[index]);
} else {
for (var i = 0; i < $scope.item2.length; i++) {
if ($scope.item2[i] == tempItem[index]) {
break;
}
if (i == $scope.item2.length - 1) {
$scope.item2.push(tempItem[index]);
}
}
}
}
}
I want to push data from one object to other (item to item2), it works well, but when i change data from item also item2 updates i dont want this.
What i missing?

As is, you are using an object reference. Then if modify one, the othes one is modified too.
You could use angular.copy
$scope.addToOrder = function(index) {
var tempItem = $scope.item;
var itemCopy = angular.copy(tempItem[index]);
if (tempItem[index].validate == true){
if (_.isEmpty($scope.item2) == true) {
$scope.item2.push(itemCopy);
} else {
for (var i = 0; i < $scope.item2.length; i++) {
if ($scope.item2[i] == tempItem[index]) {
break;
}
if (i == $scope.item2.length - 1) {
$scope.item2.push(itemCopy);
}
}
}
}
}

use angular.copy to cope by value
angular.copy($scope.item1, $scope.item2);
or
$scope.item1 = angular.copy($scope.item2);

Related

How to increment/decrement variable value only once while in a loop?

I need to decrement var "left" by 1 and only once instead of having it go through a loop and decrement if conditions pass true. But conditions are valid only if they are in a loop. How would I do this?
let key = e.key.toLowerCase()
for (i = 0; i < word.length; i++) {
if (word[i] == key) {
if (guessed[i] != key) {
console.log(e.key)
guessed[i] = key
} else {
console.log('This is where i want left--')
}
}
}
left--; //Need this to decrement only once
Store whether left has been decremented in a variable:
let key = e.key.toLowerCase()
let decrementedLeft = false;
for (i = 0; i < word.length; i++) {
if (word[i] == key) {
if (guessed[i] != key) {
console.log(e.key)
guessed[i] = key
} else {
if(!decrementedLeft){
decrementedLeft = true;
left--;
}
}
}
}
if(!decrementedLeft){
left--;
}
You can use this method:
key = e.key.toLowerCase()
Let decrement=false;
for (i = 0; i < word.length; i++) {
if(decrement==false)
if (word[i] == key) { if (guessed[i] != key) { console.log(e.key) guessed[i] = key } else { left--;
decrement=true;} } }
Or you can just break out from the loop using break
Due to more conditions I decided so. Thank you for your answers!
As a standard, got myself a few additional problems. Like first if{}else{} in the loop is executing both if and else instead of one or the other... So confusing.
let correct = 0;
let key = e.key.toLowerCase()
for (i = 0; i < word.length; i++) {
if (word[i] == key) {
if (guessed[i] != key) {
guessed[i] = key
correct = 1;
console.log(e.key)
} else {
console.log('Guessing same key')
correct = 1;
}
}
}
if (correct != 1) {
left--;
console.log('Decrementing')
tries.innerHTML += `<span>${key} </span>`
correct = 0
}

handlebars +=,-= if condition met

I've been searching the net net for a while now trying to find a way to aggregate json array values with handlebars using +=, or -= if the condition is met. however i can't seem to find any guidelines on how to properly do so. can anyone guide me on how to convert this iteration into a handlebars helper?
var table = $("#table tbody");
$.getJSON("front-end/ajax/bethistory.php", function(data) {
var value = 0;
$.each(data, function(a, b) {
if (b.action == "win") {
value += parseFloat(b.coins);
} else if (b.action == "lose") {
value -= parseFloat(b.coins);
}
var tbody = $("<tr/>").append($("<td/>").html(b.action), $("<td/>").html(value))
table.append(tbody);
});
});
something like this?
var value = 0;
Handlebars.registerHelper("this_val", function(a,b) {
if (a == "win") {
value += parseFloat(b);
} else if (a == "lose") {
value -= parseFloat(b);
}
return value;
});
for anyone who needs this. i was able to figure it out thanks to this post
Handlebars.registerHelper("compute", function(array, options) {
var new_array = "",
value = 0,
count = array.length;
for (var i = 0; i < array.length; i++) {
var coins = Number(array[i]['coins']),
action = array[i]['action'];
if (action == "win") {
if (coins > 0) {
value += coins;
}
} else if (action == "lose") {
if (coins > 0) {
value -= coins;
}
}
array[i]['running'] = value;
new_array += options.fn(array[i]);
}
return new_array;
});

How do I get a toggle button to toggle an array back and forth from descending to ascending?

I am using bubbleSort, and I can get the array to toggle from its original order to descending, but I am having trouble getting it to go from descending back to ascending. Should I just copy the bubbleSort code and flip the greater than/less than signs? Any help is appreciated!
var myStuff = [];
function myfunctionA() {
var enteredvalue = document.getElementById("numbers").value;
// alert(typeof Number(document.getElementById('numbers').value));
if (enteredvalue == "") {
alert("Input is not a number");
} else if (isNaN(enteredvalue)) {
alert('You need to enter a valid number!');
}
var elementExists = false;
var x = document.getElementById('numbers').value;
for (var i = 0; i < myStuff.length; i++) {
if (myStuff[i] == Number(x)) {
elementExists = true;
}
}
if(elementExists != true) {
myStuff.push(Number(enteredvalue));
alert('Thank You for entering a valid number.');
} else {
alert('Element is here');
}
}
function myfunctionB() {
window.alert(myStuff.length);
}
function myfunctionC() {
var sum = 0;
for(var i = 0; i < myStuff.length; i++) {
sum+=myStuff[i];
}
alert(sum);
}
function myfunctionD() {
if (myStuff.length == 0) {
alert("already empty");
} else {
myStuff = [];
}
alert("Array Empty");
}
function myfunctionE() {
alert(myStuff.join('\n'));
{
if (myStuff == []) {
alert("Enter something into Array")
}
}
}
function bubbleSort() {
var sorted = true;
var temp;
while(sorted) {
sorted = false;
for(var i = 0; i < myStuff.length-1; i++) {
if(myStuff[i] < myStuff[i+1]) {
temp = myStuff[i];
myStuff[i] = myStuff[i+1];
myStuff[i+1] = temp;
sorted = true;
}
}
}
}
First you'll need a toggle to tell which way you are going.
var isAscending = false;
Then in your bubbleSort function inside the for-statement, above the if-statement.
var sortComparison;
if (isAscending) sortComparison = myStuff[i] > myStuff[i];
if (!isAscending) sortComparison = myStuff[i] < myStuff[i];
Then replace your if-statement with:
if (sortComparison)
Finally, once you have finished sorting, you can toggle your variable:
isAscending = !isAscending;
Though, I'd recommend using a toggled variable and simply using sort() and reverse() instead.
https://jsfiddle.net/ytcax0qc/

javascript for loop dosn't loop through users created

OK so I am making a register and login for a forum using javascript and localstorage. "School assignment" My problem is that when i created multiple user and store them in the localstorage, my for loop does not loop through them all, only the first one. So i can only access the forum with the first user i create.
function login () {
if (checklogin()) {
boxAlert.style.display = "block";
boxAlert.innerHTML = "Welcome" + "";
wallPanel.style.display = "block";
} else {
boxAlertfail.style.display = "block";
boxAlertfail.innerHTML = "Go away, fail";
}
}
function checklogin (){
for (var i = 0; i < aUsers.length; i++){
if (aUsers[i].email == inputLoginMail.value && aUsers[i].password == inputLoginPassword.value){
return true;
}else{
return false;
}
}
}
how about:
function checklogin() {
var validLogin = false;
for (var i = 0; i < aUsers.length; i++) {
if (aUsers[i].email == inputLoginMail.value
&& aUsers[i].password == inputLoginPassword.value) {
validLogin = true;
break;
}
}
return validLogin;
}
Ouch! You are returning false on very first attempt. The best way is to set a variable and then check for it.
function checklogin() {
var z = 0;
for (var i = 0; i < aUsers.length; i++) {
if (aUsers[i].email == inputLoginMail.value && aUsers[i].password == inputLoginPassword.value) {
z = 1;
break;
} else {
z = 0;
}
if (z == 1) {
// User logged in
} else {
// Fake user
}
}

Checkboxes and trying to save the state of all checkboxes for the user when they return

function getFormState() {
var fields = document.getElementsByTagName('form')[0].elements;
if (fields.length === 0) {
return;
};
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
if (document.getElementByTagName('name').checked === true) {
localStorage.setItem('name', "true");
} else {
localStorage.setItem('name', "false");
}
}
}
function fillFormState() {
var fields = document.getElementsByTagName('form')[0].elements;
if (fields.length === 0) {
return;
};
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
getStatus = localStorage.getItem('name'); {
if (getStatus === "true") {
console.log("its checked");
document.getElementByTagName("name").setAttribute('checked', 'checked');
} else {
console.log("its not checked");
}
}
}
} // run the below functions when the web page is loadedwindow.onload = function () {
// check if HTML5 localStorage is supported by the browser
if ('localStorage' in window && window['localStorage'] !== null) {
// get the form state
getFormState();
// save the state of the form each X seconds (customizable)
setInterval('fillFormState()', 1 * 1000);
}
};
But it doesn't seem to work. And Im trying to figure out why. Im not very experienced with javascript so it might be quite obvious. Sorry for that. Im trying.
I'm guessing your localStorage is never being set because of this loop:
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
if (document.getElementByTagName('name').checked === true) {
localStorage.setItem('name', "true");
} else {
localStorage.setItem('name', "false");
}
}
There is no document.getElementByTagName, and you are also searching for "name" instead of your variable name.
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
if (fields[i].checked === true) { //Check the current field
localStorage.setItem(name, "true"); //Set the actual name, not "name"
} else {
localStorage.setItem(name, "false");
}
}

Categories

Resources