AngularJS dynamic Tables and ng-repeat - angularjs

I am trying to answer my own unanswered question but stuck with some weird results of my code that I can't figure out.
When I generate the whole table by entering common heights and floor numbers and then add Elevators one by one The program works fine and perfect.
But When I add some rows manually by clicking arrow signs and then add elevator, instead of adding one elevator it adds many elevators, where number of elevators = number of floors manually added.
I tried to look at code line by line, but I can't figure out, where is bug here. Please support!
My concern is problems in one of following functions mostly $scope.AddElevator
$scope.AddElevator = function(ElevatorName) {
console.log("Floor Numbers");
console.log($scope.Floors.length);
/* $scope.Floors.sort(function(a, b) {
if (a.FloorNo > b.FloorNo) {
return -1;
}
if (a.FloorNo < b.FloorNo) {
return 1;
}
// a must be equal to b
return 0;
});
*/
// CODE to ADD New Elevator in Table
for (var i = 0; i < $scope.Floors.length; i++) {
console.log(i);
$scope.Floors[i].LiftServeDetails.push({
Name: ElevatorName,
ASide: "Available",
BSide: "N/A"
});
console.log($scope.Floors[i]);
}
};
// Add Row on top of a Row
$scope.floorUp = function(floorno) {
$scope.tmpLiftServeDetails = [];
$scope.tmpLiftServeDetails = $scope.Floors[0].LiftServeDetails;
for (var i = 0; i < $scope.Floors.length; i++) {
if ($scope.Floors[i].FloorNo > floorno) {
$scope.Floors[i].FloorNo = $scope.Floors[i].FloorNo + 1;
}
}
$scope.Floors.push({
FloorNo: floorno + 1,
Level: null,
Height: 0,
Shops: 0,
LiftServeDetails: $scope.tmpLiftServeDetails
});
};
// Add Row in bottom of a Row
$scope.floorBottom = function(floorno) {
$scope.tmpLiftServeDetails = [];
$scope.tmpLiftServeDetails = $scope.Floors[0].LiftServeDetails;
for (var i = 0; i < $scope.Floors.length; i++) {
if ($scope.Floors[i].FloorNo >= floorno) {
$scope.Floors[i].FloorNo = $scope.Floors[i].FloorNo + 1;
}
}
$scope.Floors.push({
FloorNo: floorno,
Level: null,
Height: 0,
Shops: 0,
LiftServeDetails: $scope.tmpLiftServeDetails
});
};

In your floorUp and floorBottom function you are not copying the objects, you are referencing them.
Try this:
$scope.floorUp = function(floorno) {
var tmpLiftServeDetails = angular.copy($scope.Floors[0].LiftServeDetails);
for (var i = 0; i < $scope.Floors.length; i++) {
if ($scope.Floors[i].FloorNo > floorno) {
$scope.Floors[i].FloorNo = $scope.Floors[i].FloorNo + 1;
}
}
$scope.Floors.push({
FloorNo: floorno + 1,
Level: null,
Height: 0,
Shops: 0,
LiftServeDetails: tmpLiftServeDetails
});
};

Related

this.items[id].size.pop is not a function

I am trying to create an array of sizes. I am adding to the array just fine and it is displaying. I try to remove with .pop(); and it gives me the error listed in the title of this post.
this.add = function(item, id, size){
var storedItem = this.items[id];
if(!storedItem) {
storedItem = this.items[id] = {item: item, qty: 0, price: 0, size: []}. <------
}
storedItem.size += size;
storedItem.qty++;
storedItem.price = storedItem.item.price * storedItem.qty;
this.totalQty++;
this.totalPrice += storedItem.item.price;
}
this.reduceByOne = function(id){
this.items[id].size.pop(). <------------
this.items[id].qty--;
this.items[id].price -= this.items[id].item.price;
this.totalQty--;
this.totalPrice -= this.items[id].item.price;
if(this.items[id].qty <= 0) {
delete this.items[id];
}
}
I have also tried this and get the same error.
var reduceOne = this.items[id].size;
reduceOne.pop();
storedItem.size += size;
Did you mean to use push here instead of +=?
storedItem.size.push(size);

Calculate sum in array using used in object

I am new to js and I want to calculate a sum in the array. The issue is that my array is sitting in object - game. Here is my code:
var game = {
fullName: 'Mark Visp',
score: [110, 320, 50, 80],
sumScore: function () {
this.total = [];
var total = 0;
for (i = 0; i < this.score.length; i++) {
total = total + this.score[i];
}
return total
}
}
game.sumScore();
console.log(game);
I am missing something?
Thanks in advance.
Please replace with below code
var game = {
fullName: 'Mark Visp',
score: [110, 320, 50, 80],
total: 0,
sumScore: function () {
var _total = 0;
for (i = 0; i < this.score.length; i++) {
_total = _total + this.score[i];
}
this.total = _total;
}
}
game.sumScore();
console.log(game);

Two for loops in one function will not save an array after exiting for loop

I have two arrays I need to compare in a test. I am testing a filter, it reads in an array of numbers and saves to spareArray. I then click on a filter button which is also the element the int list is listed in, style. I read in the list again and save it to the second array, spareIntArray. After the readin I send the arrays to two methods, one parses string to float and the second gets ride of '-' that are in my lists I do not want to compare. However after the run of the second for loop reading in spareIntArray the array is set to undefined. I tested that the array is filled with elements by doing a log and it seems to be. I am quite confused what is happening here.
/**
* Created by nphillips on 8/11/2015.
*/
var helper = require('./../pages/helper-page.js');
var capacityPage = module.exports = {
variables: {
//the theaterStyle element list
theaterStyle: element.all(by.css("[data-style='theater']")),
},
readsInTheater: function() {
capacityPage.readsIn(capacityPage.variables.theaterStyle);
},
removesDashes: function(style, array) {
while (array.indexOf('-') !== -1) {
array.splice(array.indexOf('-'), 1);
};
console.log(array + "count ");
return array;
},
readsIn: function(style) {
var spareArray = [];
var spareIntArray = [];
style.count().then(function(count) {
console.log(count);
j = 0;
for (var i = 0; i < count; i++) {
//scrolls down the list element by element
browser.executeScript("arguments[0].scrollIntoView();", style.get(i).getWebElement());
style.get(i).getText().then(function(text) {
spareArray[j] = text;
console.log(text, spareArray[j], j);
expect(text).toEqual(spareArray[j++]);
});
}
}).then(function() {
// style.click()
browser.executeScript("arguments[0].scrollIntoView();", style.get(0).getWebElement());
style.count().then(function(count) {
console.log(count);
for (var i = 0; i < count; i++) {
//scrolls down the list element by element
browser.executeScript("arguments[0].scrollIntoView();", style.get(i).getWebElement());
style.get(i).getText().then(function(text) {
spareIntArray[j] = text;
console.log(text, spareIntArray[j], j + "frawer");
expect(text).toEqual(spareIntArray[j++]);
});
};
});
spareArray = capacityPage.stringToFloatArray(spareArray);
spareIntArray = capacityPage.stringToFloatArray(spareIntArray);
capacityPage.removesDashes(style, spareArray);
capacityPage.removesDashes(style, spareIntArray);
expect(spareArray).toEqual(spareIntArray);
});
},
stringToFloatArray: function(array) {
function int_arr(a, b) {
return parseFloat(a) - parseFloat(b);
}
array = array.sort(int_arr);
console.log(array + "float");
return array;
},
};
Is spareIntArray being undefined?. It could be because you are calling stringToFloatArray on spareIntArray before it is filled. I think that your check should be inside the promise callback. However I am a bit concerned on why you are using asynchronous data retrieval on the document. Is there a way to do it in a synchronous way? Soemething like
style.count().then(function(count) {
console.log(count);
for (var i = 0; i < count; i++) {
//scrolls down the list element by element
browser.executeScript("arguments[0].scrollIntoView();", style.get(i).getWebElement());
var text = style.get(i).getText();
spareArray.push(text);
console.log(text, spareArray[i], i);
expect(text).toEqual(spareArray[i]);
});
}
}).then(function() {
// style.click()
browser.executeScript("arguments[0].scrollIntoView();", style.get(0).getWebElement());
style.count().then(function(count) {
console.log(count);
for (var i = 0; i < count; i++) {
//scrolls down the list element by element
browser.executeScript("arguments[0].scrollIntoView();", style.get(i).getWebElement());
var text = style.get(i);
spareIntArray.push(text);
console.log(text, spareIntArray[i], i + "frawer");
expect(text).toEqual(spareIntArray[i]);
};
spareArray = capacityPage.stringToFloatArray(spareArray);
spareIntArray = capacityPage.stringToFloatArray(spareIntArray);
capacityPage.removesDashes(style, spareArray);
capacityPage.removesDashes(style, spareIntArray);
expect(spareArray).toEqual(spareIntArray);
});
});
},

Arrays dosen't seem to work correctly in ProcessingJS

I'm making a game currently for fun, and wanted to use arrays to draw levels with.
However, it seems there is some error that stops the program from actually drawing the rectangles. I've looked for pretty much every error that I could think of in the code. I've even tried re-learning the array subject on KhanAcademy, but nothing there seems to fix my problem. So I thought that StackOverflow was my last resort. You can see the game here, or if you just wanna see the pure code, it can be found here, and if you think my site will give you a virus, you can just see it here:
var sketchProc = function(processingInstance) {
with (processingInstance) {
size(400, 400);
frameRate(60);
// Setup stuff 'n stuff
noStroke();
fill(0, 0, 0);
var scene = 0;
var controlsEnable = 0;
var tufdasDebug = 0;
var tufdasLeve;
/* Key/control variables (JavaScript key codes:
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes)*/
var keyIsPressed = 0;
var key_SHIFT = 16;
var key_CTRL = 17;
// Position & Size variables
var jumperXPos = 100;
var jumperYPos = 360;
var jumperSize = 20;
// Counters
var jumperXCounter = 11;
var jumperYCounter = 11;
var shiftCounter = 11;
keyPressed = function() {
keyIsPressed = 1;
};
keyReleased = function() {
keyIsPressed = 0;
resetCounters();
};
var askForResolution = function() {
text("What resolution do you want to play in?", 100, 15);
};
var addCounters = function(amount) {
if (amount) {
jumperXCounter += amount;
jumperYCounter += amount;
shiftCounter += amount;
} else {
jumperXCounter ++;
jumperYCounter ++;
shiftCounter ++;
}
};
var resetCounters = function() {
jumperXCounter = 11;
jumperYCounter = 11;
shiftCounter = 11;
};
var controlsHandler = function() {
addCounters();
if (tufdasDebug === 1) { console.log("Handling controls..."); }
if (keyIsPressed === 1) {
if (tufdasDebug === 1) { console.log("A key is being pressed..."); }
if (controlsEnable === 0) {
if (tufdasDebug === 1) { console.log("Controls disabled..."); }
if (keyCode === key_SHIFT) {
if (tufdasDebug === 1) { console.log("Shift is being pressed."); }
scene ++;
controlsEnable = 1;
}
} else if (controlsEnable === 1) {
if (keyCode === UP && jumperYCounter > 10) {
jumperYPos -= 20;
jumperYCounter = 0;
} else if (keyCode === RIGHT && jumperXCounter > 10) {
jumperXPos += 20;
jumperXCounter = 0;
}
}
}
};
var drawIntroSequence = function(y) {
textSize(30);
text("JUMPER", 125, y + 100);
textSize(15);
text("Press SHIFT or RSHIFT to continue...\n(make sure to click inside the game first)", 65, y + 300);
};
var drawJumper = function() {
fill(0, 0, 255);
rect(jumperXPos, jumperYPos, jumperSize, jumperSize);
};
var drawtufdasLevel = function() {
fill(0, 0, 0);
rect(tufdasLevel[0], tufdasLevel[1], tufdasLevel[2], tufdasLevel[3]);
rect(tufdasLevel[4], tufdasLevel[5], tufdasLevel[6], tufdasLevel[7]);
};
draw = function() {
background(255, 255, 255);
if (scene === 0) {
drawIntroSequence(0);
var tufdasLevel = [0, 380, 400, 20, 0, 0, 400, 20]; // Space indicates a new command.
} else if (scene === 1) {
drawtufdasLevel();
drawJumper();
}
controlsHandler();
};
}};
var canvas = document.getElementById("tufdaDrawCanvas");
var processingInstance = new Processing(canvas, sketchProc);
To figure out exactly what's happening, open up your JavaScript console by opening your game in a browser, pressing the F12 key, and then going to the "Console" tab.
When your game starts, you'll see the error:
Uncaught TypeError: Cannot read property '0' of undefined at game.js:100
That tells you the error is happening on line 100 of your sketch, which is this line:
rect(tufdasLevel[0], tufdasLevel[1], tufdasLevel[2], tufdasLevel[3]);
So now you know something is wrong with your tufdasLevel variable. Let's see where you declare it. You've got one here on line 12:
var tufdasLevel;
That's your declaration, but where is your initialization? You've got one here, one line 118:
var tufdasLevel = [0, 380, 400, 20, 0, 0, 400, 20]; // Space indicates a new command.
Ah-ha! Notice how you're using the var keyword to declare another variable named tufdasLevel. This is a different variable from the one at the top of your sketch, which is the one being used on line 100. The tufdasLevel variable on line 118 is never used, and the tufdasLevel on line 12 is never initialized. So when your game tries to use that uninitialized variable, you get the error you're seeing.
It seems like you meant to initialize the variable on line 118, not declare it. Try just dropping the var keyword from line 118:
tufdasLevel = [0, 380, 400, 20, 0, 0, 400, 20]; // Space indicates a new command.
You might also put that initialization on line 12 instead.

Multidimensional Arrays and one of the fields

There is a multi-d array and I want to reach specific field in it. I have look around it but I was unable to find proper answer to my question.
My array is like that;
array-md
columns-- 0 | 1 | 2
index 0 - [1][John][Doe]
index 1 - [2][Sue][Allen]
index 2 - [3][Luiz][Guzman]
.
.
.
index n - [n+1][George][Smith]
My question is how can I reach only second column of the array? I tried name = array[loop][1]; but it says "Cannot access a property or method of a null object reference". What is the right way to do that?
Here is main part of the code.
get
var lpx:int;
var lpxi:int;
var arrLen:int = Info.endPageArray.length;
for(lpx = 0; lpx < arrLen; lpx++)
{
for(lpxi = Info.endPageArray[lpx][2]; lpxi < Info.endPageArray[lpx][1]; lpxi++)
{
if(Info._intervalSearch[lpxi] == "completed")
{
successCount++;
Info._unitIntervalSuccess.push([lpx, successCount / (Info._intervalSearch.length / 100)]);
}
}
}
set
for(lpix = 0; lpix < arrayLength; lpix++)
{
if(lpix + 1 <= arrayLength)
{
Info.endPageArray.push([lpix, Info._UnitsTriggers[lpix + 1], Info._UnitsTriggers[lpix]]);
}
else
{
Info.endPageArray.push([lpix, Info._UnitsTriggers[lpix], Info._UnitsTriggers[lpix - 1]]);
}
}
Try this:
var tempArr:Array = [];
function pushItem(itemName:String, itemSurname:String):void
{
var tempIndex:int = tempArr.length;
tempArr[tempIndex] = {};
tempArr[tempIndex][tempIndex + 1] = {};
tempArr[tempIndex][tempIndex + 1][name] = {};
tempArr[tempIndex][tempIndex + 1][name][itemSurname] = {};
}
function getNameObject(index:int):Object
{
var result:Object;
if(index < tempArr.length)
{
result = tempArr[index][index + 1];
}
return result;
}
pushItem("Max", "Payne");
pushItem("Lara", "Croft");
pushItem("Dart", "Vader");
//
trace(getNameObject(0));
trace(getNameObject(1));
trace(getNameObject(2));
Multidimensional array is an array of arrays, which you can create like this :
var persons:Array = [
['John', 'Doe'],
['Sue', 'Allen'],
['Luiz','Guzman']
];
var list:Array = [];
for(var i:int = 0; i < persons.length; i++)
{
list.push([i + 1, persons[i][0], persons[i][1]]);
}
trace(list);
// gives :
//
// 1, John, Doe
// 2, Sue, Allen
// 3, Luiz, Guzman
Then to get some data :
for(var j:int = 0; j < list.length; j++)
{
trace(list[j][1]); // gives for the 2nd line : Sue
}
For more about multidimensional arrays take a look here.
Hope that can help.

Resources