Angular values update in both elements - angularjs

I am adding same element (json object) into a list (from another list) twice using .copy to break the reference. But even after doing that when I change some values in one both of them are getting updated.
$scope.addProduct = function (item) {
var index = $scope.itemsProduct.indexOf(item);
$scope.scopItem = {};
angular.copy(item , $scope.scopItem);
for(var j in $scope.scopItem['ABC']) {
$scope.scopItem['ABC'][j].dataType='Discount';
$scope.scopItem['ABC'][j]['Discount'] = '';
}
if (index != -1) {
$scope.itemsTags.push($scope.scopItem);
$timeout(function() {
$scope.$apply(function () {
$scope.calculate($scope.scopItem);
});
}, 10);
}
};
$scope.calculateParam = function (indexQ) {
var index = $scope.itemsTags.indexOf(indexQ);
$scope.itemsTags[index]['ABC']['Discount'] = '10'; //or some other logic
}
Need help as even i am not adding the same element(using .copy) and updating the "Discount" property of one updates both??
Note: ABC is a inner list with property as "Discount" and I am changing "Discount"

Some comments:
for(var j in $scope.scopItem['ABC'])
it's absolutely incorrect and should be rewrited to
for(var j=0; j < $scope.scopItem['ABC'].length; j++)
also scopItem is changed in calculate method and stored in itemsTags

Related

AngularJS - Delete check box is not working correctly and only deleting one at a time

I've written out a block of code that allows the user to check or uncheck entities that will be added or removed via web services. My add function seems to be working correctly and provides the ability to add multiple entities. However, my delete function isn't working the same. It doesn't delete each time, and can only delete one at a time. I'm struggling since the code is effectively the same as the add, so I don't know if the issue is AngularJS related or perhaps my web service isn't working correctly.
Edit: I've actually noticed that the for loop goes through it all but doesn't select the correct id, it always starts from the first one.
var toDeleteService = [];
for (var i = 0; i < $scope.siteServices.length; i++) {
if ($scope.siteServices[i].chosen != $scope.siteServices[i].origChosen) {
if ($scope.siteServices[i].chosen == true) {
toAddService.push(i);
}
else {
toDeleteService.push(i);
}
}
}
if (toDeleteService.length > 0) {
var deleteRequest = {};
deleteRequest.services = [];
for (var i = 0; i < toDeleteService.length; i++) {
var parentServiceName = $scope.siteServices[i].parentServiceName;
var j = 0;
for (; j < deleteRequest.services.length; j++) {
if (deleteRequest.services[j].parentServiceName == parentServiceName) {
break;
}
}
if (j == deleteRequest.services.length) {
deleteRequest.services[j] = {};
deleteRequest.services[j].parentServiceName = parentServiceName;
deleteRequest.services[j].subservices = [];
}
var service = {};
service.serviceId = $scope.siteServices[i].serviceId;
deleteRequest.services[j].subservices.push(service);
}
var deleteUrl = "api/sites/" + $scope.targetEntity.siteId + "/services/" + service.serviceId;
$http.delete(deleteUrl)
.then(function (response) {
});
}
As I understood it you are trying to remove siteServices based by numbers stored in var toDeleteServices = [] so you need to access those numbers by its index. but in service.serviceId = $scope.siteServices[i].serviceId; you are using i instead.
service.serviceId = $scope.siteServices[toDeleteServices[i]].serviceId; as you need actual number of the service to delete.
If I understood your code correctly.

Infinite Digest Loop in AngularJS filter

I have written this custom filter for AngularJS, but when it runs, I get the infinite digest loop error. Why does this occur and how can I correct this?
angular.module("app", []).
filter('department', function(filterFilter) {
return function(items, args) {
var productMatches;
var output = [];
var count = 0;
if (args.selectedDepartment.Id !== undefined && args.option) {
for (let i = 0; i < items.length; i++) {
productMatches = items[i].products.filter(function(el) {
return el.Order__r.Department__r.Id === args.selectedDepartment.Id;
});
if (productMatches.length !== 0) {
output[count] = {};
output[count].products = productMatches;
output[count].firstProduct = items[i].firstProduct;
count++;
}
}
}
return output;
};
}).
This is the relevant HTML:
<tr class='destination' ng-repeat-start='pickupAccount in pickupAccounts | department : {"selectedDepartment": selectedDepartment, "option": displayExclusive }'>
<!-- td here -->
</tr>
displayExclusive is boolean.
I have written this custom filter for AngularJS, but when it runs, I get the infinite digest loop error.
Keep in mind that filter should return array of the same object structure. When we activate filter, it fires digest cycle that will run over our filter again. If something changed in output list - fires new digest cycle and so on. after 10 attempts it will throw us Infinite Digest Loop Exception
Testing
This empty filter will works (100%). Actually we do nothing here but return the same object that filter receives.
filter('department', function(filterFilter) {
return function(items, args) {
var output = items;
return output;
};
})
Now the main idea is: write some condition to push to output objects from input list a.e. items based on some if statement, a.e.
var output = [];
if (args.selectedDepartment.Id !== undefined && args.option) {
angular.forEach(items, function(item) {
if(<SOME CONDITION>) {
output.push(item);
}
});
}
By this way it will work too.
our case:
we have this logic:
productMatches = items[i].products.filter(function(el) {
return el.Order__r.Department__r.Id === args.selectedDepartment.Id;
});
if (productMatches.length !== 0) {
output[count] = {};
output[count].products = productMatches;
output[count].firstProduct = items[i].firstProduct;
count++;
}
Here we completely modified object that has been stored in output.
So next digest cycle our items will change again and again.
Conclusion
The main purpose of filter is to filter list and not modify list object content.
Above mentioned logic you wrote is related to data manipulation and not filter. The department filter returns the same length of items.
To achieve your goal, you can use lodash map or underscorejs map for example.
This happens when you manipulate the returned array in a way that it does not match the original array. See for example:
.filter("department", function() {
return function(items, args) {
var output = [];
for (var i = 0; i < items.length; i++) {
output[i] = {};
output[i] = items[i]; // if you don't do this, the next filter will fail
output[i].product = items[i];
}
return output;
}
}
You can see it happening in the following simplified jsfiddle: https://jsfiddle.net/u873kevp/1/
If the returned array does have the same 'structure' as the input array, it will cause these errors.
It should work in your case by just assigning the original item to the returned item:
if (productMatches.length !== 0) {
output[count] = items[i]; // do this
output[count].products = productMatches;
output[count].firstProduct = items[i].firstProduct;
count++;
}
output[count] = {};
Above line is the main problem. You create a new instance, and ng-repeat will detect that the model is constantly changed indefinitely. (while you think that nothing is changed from the UI perspective)
To avoid the issue, basically you need to ensure that each element in the model remains the 'same', i.e.
firstCallOutput[0] == secondCallOutput[0]
&& firstCallOutput[1] == secondCallOutput[1]
&& firstCallOutput[2] == secondCallOutput[2]
...
This equality should be maintained as long as you don't change the model, thus ng-repeat will not 'wrongly' think that the model has been changed.
Please note that two new instances is not equal, i.e. {} != {}

AngularJS - create object array where label is $translated

I have the following array:
vm.roles = ['ROLE1', 'ROLE2', 'ROLE3', 'ROLE4'];
and I need this form of array:
vm.translatedRoles = [{id:0, label:'Role1'}, {id:1, label:'Role2'}, ...]
Therefore I wrote this function to transfer from vm.roles to vm.translatedRoles.
My Problem now is that translatedRoles stays empty, so there are no objects in it. Does anyone know why?
function translateRoles() {
var translatedRoles = [];
for(var i = 0; i < vm.roles.length; i++) {
$translate(vm.roles[i]).then(function(text) {
var role = {};
role.id = i;
role.label = text;
translatedRoles.push(role);
});
}
return translatedRoles;
}
That can't work. $translate() returns a promise. The function passed to $translate is executed later, asynchronously, when the translations are available. So, the return statement happens before translatedRoles is populated by the function.
You need to return a promise of array, or hope that the translations are already available and use $translate.instant():
function translateRoles() {
var translatedRoles = [];
for (var i = 0; i < vm.roles.length; i++) {
translatedRoles.push({
id: i,
label: $translate.instant(vm.roles[i]);
});
}
return translatedRoles;
}

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);
});
});
},

Splice array within array

How can I splice an array within another array?
I'm trying to create a game for kids in my class. Some kind of a trivia history question creator. How to splice the MasterArray so that I would get rid of sub-arrays (Hard-England and Medium-England) within the allEnglandArray. Because the "MasterArray.splice()" seem to be affecting - splicing only the allEngland array, or the allFrance array. But I need to get rid of those sub-arrays...
My code:
var Easy-England:Array = ["item1","item2","item3","item4","item5"];
var Medium-England:Array = ["item6","item7","item8"];
var Hard-England:Array = ["item9","item10"];
var allEngland:Array = [Easy-England,Medium-England,Hard-England];
var Easy-France:Array = ["item11","item12","item13","item14","item15"];
var Medium-France:Array = ["item16","item17","item18"];
var Hard-France:Array = ["item19","item20"];
var allFrance:Array = [Easy-France,Medium-France,Hard-France];
// the list of countries goes on and on and on... (Italy, Hungary, etc.)
var allStuff:Array = [allEngland, allFrance, etc.];
var MasterArray:Array;
// FUNCTIONS
// clear MasterArray - first I clear out completely the MasterArray
function clearMasterArray():void
{
MasterArray.splice(0);
}
// update MasterArray - than I fill the MasterArray with data according to checkBoxes
function updateMasterArray():void
{
for (var i:int = 0; i<checkBoxBlock.myCheckBoxes.length; i++)
{
if (checkBoxBlock.myCheckBoxes[i].selected)
{
MasterArray.push(allStuff[i]);
}
}
}
// splice MasterArray - last thing I do is splice the items according to student's proficiency level, referred to as "studentPL".
function spliceMasterArray():void
{
if (studentPL == 1)
{
for (var i:int = 0; i<allStuff.length; i++)
{
allStuff[i].splice(5,5);
}
}
if (studentPL == 2)
{
for (var i:int = 0; i<allStuff.length; i++)
{
allStuff[i].splice(8,2);
}
}
if (studentPL == 3)
{
for (var i:int = 0; i<allStuff.length; i++)
{
trace("no need to splice");
}
}
}
And after this I call those functions in another function in this order...
function creatorFunction():void
{
clearMasterArray();
updateMasterArray();
spliceMasterArray();
}
Instead of:
var allEngland:Array = [Easy-England,Medium-England,Hard-England];
try this:
var allEngland:Array = Easy-England.concat(Medium-England, Hard-England);
This way you will have a 'flat' array (no sub-arrays), so it will be easier to deal with.

Resources