Can't push new data using localstorage


#1

I want to store new data to the object but I’m having an error. Help will be much appreciated.

$scope.myLunch = [ {food: ‘Example’}];
$scope.myLunch = $localStorage.myLunch;

  $scope.savelunch = function(id) {

        $scope.myLunch.push({food: id });
    $localStorage.myLunch = myLunch;
    $scope.myLunch = $localStorage.myLunch;
  };

#2

What does the error say? try $localStorage.myLunch = $scope.myLunch


#3

Nothing happens. The output of the expression is literally “{{myLunch}}”


#4

What are you trying to do? Can you post the html?


#5

I’m trying to store data inside the object myLunch.

{{myLunch}}

    <h3><b>{{item.FoodName}}</b></h3>
    <p>Calories: {{item.Calories}}</p>
    <p>Fat: {{item.Fat}}</p>
    <p>Protein: {{item.Protein}}</p>
    <p>Carbohydrates: {{item.Carbohydrates}}</p>

  </ion-item>
</ion-list>
<ion-list>
  <ion-item ng-repeat="one in myLunch" class="item-text-wrap">

    <h3><b>{{one.food}}</b></h3>

  </ion-item>
</ion-list>
<button class="button-small button-full button-clear" ng-click="savelunch(addrecipe)">

Add Food


#6

try

$scope.myLunch.push({'food': 'id'});

and is this $localStorage of ngStorage ?


#7

yes i’m using ngStorage


#8

@chocoholic

Instead of this

$scope.savelunch = function(id) {

    $scope.myLunch.push({food: id });
$localStorage.myLunch = myLunch;
$scope.myLunch = $localStorage.myLunch;
  };

Do this:

 $scope.savelunch = function(id) {

    $localStorage.myLunch.push({"food":"id"});
$scope.myLunch = $localStorage.myLunch;
 };

if you already have object in local storage then directly push new entries to localstorage object.
This works. i am doing this

and key value pairs should be in double quotes