myApp.controller('editCtrl', function ($scope, adFactory) { $scope.adList = adFactory.ads; $scope.insertNewAd = function(){ adFactory.insertAd($scope.myAd); }; console.log($scope.adList) }); 

Help with problem solving. It is impossible to add an object to an array without changing the old ones. The object is added as if, but at the same time all old saved objects are overwritten.

 myApp.service('adFactory', function() { var self = this; this.ads = []; this.insertAd = function(poster){ function getAds(){ self.ads = JSON.parse(localStorage.getItem('adstorage')); }; self.ads.push({ id: _.uniqueId(), title: poster, description: poster }); localStorage.setItem ('adstorage', JSON.stringify(self.ads)); }; }); 

  • The essence of the problem is incomprehensible. Indicate what result was expected and what was obtained. - Igor Golovin
  • It was expected that by clicking on the button, a function will be triggered by adding an object to the array and storing it in localstorage. As a result, an object is added to the array, but old objects are overwritten, and data from the new object is saved in them. - Artyom Sapsay
  • and if you use debugging : self.ads = JSON.parse(localStorage.getItem('adstorage')); After this line to make output to the content console ads array contains old data? - Bald
  • @ArtyomSapsay lay out a reproducible example with a bug, it’s not clear from the current code where it can overwrite. - Igor Golovin
  • Put in the message the code of the controller that calls the function of adding data to the array. - Artyom Sapsay

1 answer 1

Found an error, instead of function(poster) it was necessary function(myAd) . myAd is my ng-model="myAd" which I use on the form to add data to the array. Everything is working.

 this.insertAd = function(myAd){ function getAds(){ self.ads = JSON.parse(localStorage.getItem('adstorage')); }; self.ads.push({ id: _.uniqueId(), title: myAd.title, description: myAd.description }); localStorage.setItem ('adstorage', JSON.stringify(self.ads)); };