get back the last updated data from local storage - angularjs

i want to retrieve my last updated value from local storage.
my code is:
$scope.saved = localStorage.getItem('ids');
$scope.ids = JSON.parse($scope.saved);
localStorage.setItem('ids', JSON.stringify($scope.ids));
console.log($scope.ids)
$scope.LogIn = function() {
if($scope.id=='1'){
$state.go('app.playlists');
}
$scope.ids = [];
$scope.ids.push({text:$scope.id});
localStorage.setItem('ids', JSON.stringify($scope.ids));
};
using this code i am not getting the value in console instead getting 'undefined'

you can use $scope.ids.length-1 to get the last index of the array
$scope.saved = localStorage.getItem('ids');
$scope.ids = JSON.parse($scope.saved);
console.log($scope.ids[$scope.ids.length-1])

Related

AngularJS is setting value for unrelated scope variable

I have the following angular code to initialize an angular form. It returns a mostly null record except for a couple of dates and employee info.
I was trying to create a scope variable to keep the original record for comparison purposes after the form is filled out. This is what $scope.TechSheetInfoStatic is for.
For our purposes here, I set $scope.TechSheetInfo.Customer.Email to a dummy value. This, while updating $scope.TechSheetInfo, also updates $scope.TechSheetInfoStatic. Why?
$scope.initializeTechSheet = function() {
$scope.TechSheetInfo = [];
$scope.TechSheetInfoStatic = [];
$scope.customerIDDisabled = false;
$scope.orderIDDisabled = false;
const successFunction = function(response) {
$scope.TechSheetInfo = response.data;
$rootScope.customerInfo = response.data.Customer;
$scope.TechSheetInfoStatic = response.data;
$scope.TechSheetInfo.Customer.Email = "bobo#bobo.com";
alert(JSON.stringify($scope.TechSheetInfo.Customer));
alert(JSON.stringify($scope.TechSheetInfoStatic.Customer));
};
const failureFunction = function(response) {
//console.log('Error' + response.status);
};
TechSheetFactory.ITS(successFunction, failureFunction);
};
Use angular.copy to make a deep copy:
const successFunction = function(response) {
$scope.TechSheetInfo = response.data;
$rootScope.customerInfo = response.data.Customer;
̶$̶s̶c̶o̶p̶e̶.̶T̶e̶c̶h̶S̶h̶e̶e̶t̶I̶n̶f̶o̶S̶t̶a̶t̶i̶c̶ ̶=̶ ̶r̶e̶s̶p̶o̶n̶s̶e̶.̶d̶a̶t̶a̶;̶
$scope.TechSheetInfoStatic = angular.copy(response.data);
$scope.TechSheetInfo.Customer.Email = "bobo#bobo.com";
alert(JSON.stringify($scope.TechSheetInfo.Customer));
alert(JSON.stringify($scope.TechSheetInfoStatic.Customer));
};
Since response.data is an object. The assignment statement assigns a reference value to the variable. The angular.copy function will create a new object and copy the contents to the new object.
A variable holding an object does not "directly" hold an object. What it holds is a reference to an object. When you assign that reference from one variable to another, you're making a copy of that reference. Now both variables hold a reference to an object. Modifying the object through that reference changes it for both variables holding a reference to that object.
For more information, see Pass-by-reference JavaScript objects.

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

Two Objects arrays and concat

i have two arrays that are both connected to a scope (http get etc.):
$scope.allShops
that hold all the shop details and
$scope.allCds
that hold all the cd's
both work fine and the Ng-Repeat gives me all the output (individually) i need, i however would like to build a search that allows me to search on the cd name and on the shop name from the same search field (using a label to mention if its a shop or a cd to avoid confusion). So i came up with this:
$scope.allShops = [];
$scope.allCds = [];
var jointData1 = '';
var jointData2 = '';
var SearchAll = '';
var jointData1 = $scope.allShops;
console.info(jointData1);
var jointData2 = $scope.allCds;
console.info(jointData2);
var searchAll = jointData1.concat(jointData2);
console.info(searchAll)
But all the logs are empty, if i place the log inside the succes.array function it shows me the data object but placing the log with the scope outside give me nothing. How do i get the data outside the array function and able to concat the two scope?
Your console.info calls will be empty because the $http service hasn't got the data back yet.
You'd have to do this after the data is returned by using a promise (.then())
Just try this
function merge_options(obj1,obj2){
var obj3 = {};
for (var attrname1 in obj1) {
obj3[attrname1] = obj1[attrname1];
}
for (var attrname2 in obj2) { obj3[attrname2] = obj2[attrname2]; }
return obj3;
}
merge_options(obj1,obj2);

angularfire: Having trouble getting a Firebase array from my factory with $asArray()

I've got a factory that gets my data from Firebase, and I want my controller to be able to access it. However, when I console.log the data in my controller, it isn't the Array[10] that I would expect it to be, but rather an Array with keys 0,1,2,..10, $$added, $$error, $$moved,... and so on. However, when I skip out on using the factory, and use $asArray() method on my firebase ref directly in my controller it shows up nicely as an Array[10]
In my factory, this is what it looks like..
var listingsref = new Firebase("https://something.firebaseio.com");
var sync2 = $firebase(listingsref);
var products = sync2.$asArray();
factory.getProducts = function(){
return products;
};
Controller
$scope.products = marketFactory.getProducts();
console.log($scope.products) in my controller should be Array[10], but instead it's an Array with the data + a lot more $$ methods. Anyone know what's going on? Thanks
EDIT: Full Factory File
(function(){
var marketFactory = function($firebase){
var listingsref = new Firebase("https://something.firebaseio.com");
var sync2 = $firebase(listingsref);
var products = sync2.$asArray();
var factory = {};
factory.getProducts = function(){
console.log(products);
return products;
};
factory.getProduct = function(productId){
for(var x = 0; x<products.length ;x++){
if(productId == products[x].id){
return {
product:products[x],
dataPlace:x
};
}
}
return {};
};
factory.getNextProduct = function(productId, e){
var currentProductPlace = factory.getProduct(productId).dataPlace;
if (e=="next" && currentProductPlace<products.length){
return products[currentProductPlace+1];
}
else if(e=="prev" && currentProductPlace>0){
return products[currentProductPlace-1];
}
else{
return {};
}
};
factory.componentToHex = function(c){
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
};
factory.rgbToHex = function(r,g,b){
return "#" + factory.componentToHex(r) + factory.componentToHex(g) + factory.componentToHex(b);
};
factory.hexToRgb = function(hex) {
if(hex.charAt(0)==="#"){
hex = hex.substr(1);
}
var bigint = parseInt(hex, 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return r + ", " + g + ", " + b;
};
factory.parseRgb = function(rgb){
rgb = rgb.replace(/\s/g, '');
var red = parseInt(rgb.split(',')[0]);
var green = parseInt(rgb.split(',')[1]);
var blue = parseInt(rgb.split(',')[2]);
return {
r:red,
g:green,
b:blue
};
};
return factory;
};
marketFactory.$inject = ['$firebase'];
angular.module('marketApp').factory('marketFactory', marketFactory);
}());
This snippet gets a synchronized AngulareFire array of products:
var products = sync2.$asArray();
The AngularFire documentation is a bit off on this point: what you get back from $asArray() is not an array, but the promise of an array. At some point in the future your products variable will contain an array. This is done because it may take (quite) some time for your array data to be downloaded from Firebase. Instead of blocking your code/browser while the data is downloading, it returns a wrapper object (called a promise) and just continues.
Such a promise is good enough for AngularJS: if you simply bind products to the scope and ng-repeat over it, your view will show all products just fine. This is because AngularFire behind the scenes lets AngularJS know when the data is available and Angular then redraws the view.
But you said:
console.log($scope.products) in my controller should be Array[10]
That is where you're mistaken. While AngularFire ensures that its $asArray() promise works fine with AngularJS, it doesn't do the same for console.log. So your console.log code runs before the data has been downloaded from Firebase.
If you really must log the products, you should wait until the promise is resolved. You this this with the following construct:
products.$loaded().then(function(products) {
console.log(products);
});
When you code it like this snippet, the data for your products will have been downloaded by the time console.log runs.
Note that the object will still have extra helper methods on it, such as $add. That is normal and also valid on an array. See the documentation for FirebaseArray for more information on what the methods are, what they're for an how to use them.
So I edited the code in the plnkr at http://plnkr.co/M4PqojtgRhDqU475NoRY.
The main differences are the following:
// Add $FirebaseArray so we can extend the factory
var marketFactory = function($firebase, $FirebaseArray){
var listingsref = new Firebase("https://something.firebaseio.com");
// Actually extend the AngularFire factory and return the array
var MarketFactory = $FirebaseArray.$extendFactory(factory);
return function() {
var sync = $firebase(listingsref, {arrayFactory: factory});
return sync.$asArray();
};
Check out https://www.firebase.com/docs/web/libraries/angular/guide.html#section-extending-factories for more information on extending AngularFire entries. You will likely need to make some adjustments to the rest of the factory code.

Angularjs: Assigning Array within object

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...

Resources