localStorage in angular and with objects

时间:2017-10-11 11:22:56

标签: angularjs object local-storage

这是我的代码的简化版本,但是我需要能够将每个输入字段的输出存储在localStorage中,而不会相互覆盖。

Atm,它甚至不起作用。我必须填写两个输入才能保存任何内容。

var app = angular.module("app", []);

app.controller("IndexController", ["$scope", function($scope) {

  this.list = {
    "mandag":   {},
    "tirsdag":  {}
  };


  //LOCALSTORAGE
  this.Save = () => {
    localStorage.setItem("Ret", JSON.stringify(this.list.mandag));
  }

    this.addFood = (day, title) => {
      this.list[day] = {
        "food": title,
        "ingredients": []
      };
      console.log(this.list);

    }

 
  this.removeFood = (day) => {
    this.list[day].food = "";
  }

}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<head>
    <meta charset="utf-8">
    <title></title>
  </head>

  <body ng-app="app" >
    <div ng-controller="IndexController as vm">
        <div ng-repeat="(day, item) in vm.list track by $index">
          <h3>{{day}}</h3>
          <form class="" name="ret" ng-submit="vm.addFood(day, vm.newFood[$index]);vm.newTodo[$index] = ''">
            <input placeholder="Ædelse" type="text"  id="foo" ng-model="vm.newFood[$index]" ng-disabled="item.food" value="" required/>
            <button ng-disabled="ret.$invalid" ng-click="submitted=true; vm.Save()" ng-hide="submitted">Go</button>
          </form>
          <button ng-click="vm.removeFood(day); submitted=false" ng-show="submitted">X</button>
        </div>

    </div>

    
  </body>

Codepen version

1 个答案:

答案 0 :(得分:0)

我通过删除HTML中的ng-click =“vm.Save()”并稍微重新整理我的javascript来解决这个问题:

    this.Save = () => {
      localStorage.setItem("Ret", JSON.stringify(this.list));
    }

    this.addFood = (day, title) => {
      this.list[day] = {
        "food": title,
        "ingredients": []
      };
      console.log(this.list);

      this.Save(); 
    }