I have a problem with my controller and my factory my code is here:
this is my factory
` var zupa_io = angular.module(‘zupa.zfactory’, []);
zupa_io.factory('zupafactory',function($http){
// in here I retrieve my data in localStorage
var products = angular.fromJson( window.localStorage['zupacart'] || '[]' );
// in here I store my data in localStorage
function zupapersist(){
window.localStorage['zupacart'] = angular.toJson(products);
}
return {
// this is my function for save
ZupaSaveCart:function(prod){
products.push(prod);
zupapersist();
console.log(products);
},
}
});`
my problem is when a try save my data, show me this error (products.push is not a function) but de products is present.
please help me
thank you, but now a litle question more please.
when a try recover from localStorage, show me an object like this [object Object] but I can’t converto to Json
this is my code is in the same factory
` var zupa_io = angular.module(‘zupa.zfactory’, );
zupa_io.factory(‘zupafactory’,function($http){
var products = angular.fromJson( window.localStorage['zupacart'] || '[]' );
function zupapersist(){
window.localStorage['zupacart'] = angular.toJson(products);
}
return {
ZupaSaveCart:function(prod){ //create cart
Object.assign(products, prod);
//products.push(prod);
zupapersist();
console.log(products);
},
ZupaShowCart:function(){ // this function show me data from localStorage
return products; // but this function return an object like this [object Object]
},
}
});
// this is my controller for display data cart
// shoping cart controller
zupa_io.controller('CartCtrl', function($scope,zupafactory){
//console.log(products);
$scope.zupaproduct = zupafactory.ZupaShowCart();
console.log(parser); // THIS SHOW ME OBJECT [object Object]
});
`
I try to convert this object to Json, but not working, I try convert using (angular.fromJson(), Json.parse(), JSON.stringify() ) but nothing working, please help me
Hi @roma35, i’m not used to this syntax, so i’ve tried my best to figure it out, but this should work properly I think. Let’s test it and tell me what happen now
var zupa_io = angular.module('zupa.zfactory', []); zupa_io.factory('zupafactory',function($http){
var products = angular.fromJson( window.localStorage['zupacart'] || '[]' );
products = Object.assign(products, products);
function zupapersist(){
window.localStorage['zupacart'] = angular.toJson(products);
}
return {
ZupaSaveCart:function(prod){ //create cart
//products.push(prod);
zupapersist();
console.log(products);
},
ZupaShowCart:function(){ // this function show me data from localStorage
return products; // but this function return an object like this [object Object]
},
}
});
// this is my controller for display data cart// shoping cart controller
zupa_io.controller('CartCtrl', function($scope,zupafactory){
//console.log(products);
$scope.zupaproduct = zupafactory.ZupaShowCart();
console.log(parser); // THIS SHOW ME OBJECT [object Object]
});