Angularjs: Assigning Array within object - arrays

I am having an issue with losing data within an array when i try to assign it to a new array.
My object im using is as follows:
$scope.shops = [
{
name: "Kroger",
items: [ { itemName: "Chips"} ]
}
];
This is the code for the functions im using, it may be a callback issue? or something? Im losing the items info for the shop.
$scope.addItem = function(newItem, newShop){
var x = findShop(newShop);
x.items.push(newItem);
$scope.shops.push(x);
};
findShop = function(shopTag){
var old = angular.copy($scope.shops);
var tar = {
name: shopTag,
items: []
};
$scope.shops = [];
angular.forEach(old, function(shop, key){
if(shop.name === shopTag) {
tar.items = angular.copy(shop.items);
}
else {
$scope.shops.push(shop);
}
});
return tar;
};
the goal is to have the findShop function return a shop with the correct name, with empty items if there wasnt a shop previously, or with items full of the items if the shop was already created. then the addItem will push the item into the shop.items array and push the shop into the $scope
Any help is greatly appreciated!!!

You are right , it is this line which is causing the problem ,
tar.items = shop.items;
Try using it like this ,
tar.items = angular.copy(shop.items);

var old = $scope.shops; // old and $scope.shops point to the same place
..........
$scope.shops = []; // you assigned a new array that overrides the data
............
angular.forEach(old, function(shop, key){ // for each on an empty array????
If you dont want to point to the same reference use:
var copiedObject = angular.copy(objToCopy);

I guess the array is getting empty even before for loop.
Var old is reference to shops array, which you are making empty before foreach.. effectively making old empty...

Related

How to stop original list from updating when cloned list is updated

I want to stop self.lineDetails from being updated when I update self.modifiedLineDetails.
self.modifiedLineDetails = [];
angular.forEach(self.lineDetails, function (value1, index1) {
var lineDetail = self.lineDetails[index1];
self.modifiedLineDetails.push(lineDetail)
});
console.log(self.lineDetails)
angular.forEach(self.modifiedLineDetails, function (value10, index10) {
var modifiedLineDetail = self.modifiedLineDetails[index10];
if (modifiedLineDetail.SelectedCustomers.length > 0) {
modifiedLineDetail.SelectedCustomers = 1;
} else {
modifiedLineDetail.SelectedCustomers = 0
}
});
console.log(self.modifiedLineDetails)
Previously I just assigned it like this self.modifiedLineDetails = self.lineDetails then I updated self.modifiedLineDetails but it wasn't working so I tried pushing it per line but self.lineDetails keeps updating.
You should clone an array and then modify your new array, one way to do this is using
spread operation ...
Here is the example of it:
var initialarray = [1,2,3,4];
var modification = [...initialarray];
modification.push(5);
console.log(initialarray);
console.log(modification);
Since the problem seems to be occurring because I was using angular. I researched and found angular.copy which creates a deep copy. The code below worked for me.
self.modifiedLineDetails = angular.copy(self.lineDetails);

angularjs - custom property become empty

I am trying to unshift a object to existing array list. But when i do that, i am getting one of the value is empty. what is the correct way to push a new object to existing array in angularjs?
here is my code :
var staticPhase = {
"DisciplineId": "0",
"DisciplineName": "All",
"PhaseId": "0",
"PhaseName": "All" // but this is being converted as ''
}
if($scope.firstLoad) {
var newList = angular.copy( $scope.project.ProjectSummaryFilter ); //taking a copy of existing array
var filterById = $filter('filter')(newList, { ProjectId : $scope.projectId })[0];
staticPhase.ProjectId = filterById.ProjectId;
staticPhase.ProjectName = filterById.ProjectName;
staticPhase.SubProjectId = filterById.SubProjectId;
staticPhase.SubProjectName = filterById.SubProjectName;
}
var phaseList = $scope.project.ProjectSummaryFilter;
phaseList.unshift(staticPhase) //adding static phase to array;
The standard JavaScript push() method should work:
var phaseList = $scope.project.ProjectSummaryFilter;
phaseList.push(staticPhase);

Storing a list of Items in Cookie in Angular

im am trying to store a list of items in a cookie.
For Testing-Examples i use a list of citys.
It works so far but i always get the
SQLiteManager_currentLangue: and the XSRF-TOKEN: with it.
I dont really have an idea how to get rid of them both.
Any suggestions?
$scope.addToList = function(name,id) {
var cityToAdd = name;
var cityToAddID = id;
// ADD A CITY TO THE COOKIE -> WORKS
$cookies.put(cityToAddID, cityToAdd);
// SHOW THE NEW CITY_LIST ->WORKS
var allCitys = $cookies.getAll();
console.log(allCitys);
// PUT ALL INTO AN ARRAY -> WORKS
var favouritesFromCookie = [];
$.each(allCitys, function(index, value) {
console.log(value);
favouritesFromCookie.push(value);
});
// PUT THE ARRAY OF CITYS INTO A SCOPE_VARIABLE
$scope.favouriteFinal = favouritesFromCookie;
// GET RID OF THE LAST TWO ELEMENTS
}
You could give your own cookies a recognizable label and then grab that conditionally when you're compiling your array. Like so:
$cookies.put('city.' + cityToAddID, cityToAdd);
...
$.each(allCitys, function(index, value) {
if (index.indexOf('city.') == 0) { favouritesFromCookie.push(value) }
});

Testing Angular Filter That Returns An Array with Jasmine

So, I'm having issues testing an angular filter that takes an array that has previously been sorted by a group property. It uses a flag property to indicate that the item is the first observation of that group, and then false for subsequent observations.
I'm doing this to have a category header in the UI with an ng-repeat directive.
When I test the filter, the output does not return the array with the flags unless I create new objects for the return array. This is a problem, because it causes an infinite loop when running in a webpage. The code works in the webpage when it just adds a flag property to the input object.
Is there some additional step I should be taking to simulate how angular handles filters so that it outputs the proper array?
This is what my test looks like right now.
describe('IsDifferentGroup', function() {
var list, itemOne, itemTwo, itemThree;
beforeEach(module("App.Filters"));
beforeEach(function () {
list = [];
itemOne = new ListItem();
itemTwo = new ListItem();
itemThree = new ListItem();
itemOne.group = "A";
itemTwo.group = "B";
itemThree.group = "C";
list.push(itemOne);
list.push(itemOne);
list.push(itemOne);
list.push(itemOne);
list.push(itemTwo);
list.push(itemThree);
list.push(itemThree);
list.push(itemThree);
list.push(itemThree);
list.push(itemThree);
});
it('should flag the items true that appear first on the list.', (inject(function (isDifferentGroupFilter) {
expect(list.length).toBe(10);
var result = isDifferentGroupFilter(list);
expect(result[0].isDifferentGroup).toBeTruthy();
expect(result[1].isDifferentGroup).toBeFalsy();
expect(result[4].isDifferentGroup).toBeTruthy();
expect(result[5].isDifferentGroup).toBeTruthy();
expect(result[6].isDifferentGroup).toBeFalsy();
expect(result[9].isDifferentGroup).toBeFalsy();
})));
});
And here is something like the code with the filter:
var IsDifferentGroup = (function () {
function IsDifferentGroup() {
return (function (list) {
var arrayToReturn = [];
var lastGroup = null;
for (var i = 0; i < list.length; i++) {
if (list[i].group != lastGroup) {
list[i].isDifferentGroup = true;
lastAisle = list[i].group;
} else {
list[i].isDifferentGroup = false;
}
arrayToReturn.push(list[i]);
}
return arrayToReturn;
});
}
return IsDifferentGroup;
})();
Thanks!
I figured out my issue.
When I was passing the items into the list, I just pushed a pointer to an item multiple times. I was not passing in unique objects so the flag was being overridden by the following flag in the array(I think). So, I just newed up 10 unique objects using a loop, pushed them into the array and ran it through the filter. And it worked.
I'm not entirely sure my analysis is correct about the override, because itemTwo was not being flagged as unique when it was the only itemTwo in the array. But the test is working as I would expect now so I'm going to stop investigating the issue.

Unable to remove the elements still the array get cleared

I am fetching the data from the server each 10 sec, in this, i am getting 3 type of the data,
After the timeout call, i am removing the existing data, i can witness the console show that the array clears, but the elements still keep append upon.
how can i clear both elements in the DOM and unbind as well..
my close function is keep called, but the elements not remove from DOM.
my single view :
singleton.view = Backbone.View.extend({
tagName :'article',
template0 : function(value){
var label = value === 0 ? "projectName" : value === 1 ? "assignedTo" :"projectName";
return _.template("<a href='#'><%= "+label+" %></a>");
},
template1 : _.template($('#boardTemplate').html()),
initialize :function(prams){
this.template = this['template'+0](prams.subTempNo);
},
close:function(){
console.log('clean up') // i am getting consoled
this.unbind();// i am unbinding
this.remove();// i am removing
},
render:function(){
var temp = this.template;
this.$el.html(temp(this.model.toJSON()));
return this;
}
});
return singleton.view;
in the views :
listViewAppender:function(item,i){
var listElement = new singleton.view({model:item,tempNo:0,subTempNo:i,tagName:'li'});
listElement.close(); // whenever i call the new instance i am removing old stuff..
this.$el.find('.'+this.classItems[i]).append(listElement.render().el);
},
How can i fix this issue.. any correct approach pelase..
Ok just a quick rework.....you're going to have to test it out. Comment with what happens and I'll correct the code below.
Can you try
listViewSet:function(key,i){
var l = this.listCatch.length;
if(l > 0){
for (var i = 0; i < l; i++) {
console.log(this.listCatch[i]);
this.listCatch[i].remove();
}
}
this.listCatch = [];
_.each(this.listCollection.models, function(model){
that.listViewAppender(model,i); //setting agian.
});
},
listViewAppender:function(item,i){
var listElement = new singleton.view({model:item,tempNo:0,subTempNo:i,tagName:'li'});
console.log(listElement);
this.$el.find('.'+this.classItems[i]).append(listElement.render().el);
this.listCatch[i] = listElement;
},
I gone through across my functions, i find the issue in the line of this.listCatch[i] = listElement; wrongly declared.
Later i declared the array by manually, it's works fine. in my initialize i introduced 3 arrays, what i required now it works fine.
this.listCatch = [];
for(var i=0;i<this.listItems.length; i+=1){
this.listCatch[i] = [];
}
So before pushing the model to array, now the array introduced solved the issue.

Resources