LocalStorage激活两次以存储Object

时间:2016-06-02 09:58:20

标签: angularjs local-storage

我尝试将对象存储到LocalStorage中,但是当我触发setItem时,它会存储两个对象(重复)。以下是我的代码;

HTML

<form class="clearBoth"  ng-submit="addProject(projectInfo)">
      <div class="list" ng-model="projectInfo">
          <label class="item item-input item-stacked-label">
              <span class="input-label">Project Name</span>
              <input type="text" ng-model="projectInfo.name" placeholder="PSN" required>
          </label>


          <label class="item item-input item-stacked-label">
              <span class="input-label">Host</span>
              <input type="text" ng-model="projectInfo.host"  placeholder="http://psn.com.my" required>
          </label>

        <label class="item item-input item-stacked-label">
            <span class="input-label">Instance</span>
            <input type="text" ng-model="projectInfo.instance" placeholder="PSN" required>
        </label>

      </div>


      <button class="button button-block button-positive" ng-click="addProject(projectInfo)">Block Button</button>
      <button class="button button-block button-assertive" ng-click="removeProject()">Block Button</button>
  </form>

控制器

.controller("ProjectAddCtrl", function($scope) {

    $scope.addProject = function (projectInfo) {

        var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];

        $scope.projects = [{
        name: "",
        host: "",
        instance: ""
        }];

    oldItems.push(projectInfo);
    localStorage.setItem('itemsArray', JSON.stringify(oldItems));

};

    $scope.removeProject = function () { localStorage.clear(); };

    console.log(JSON.parse(localStorage.getItem('itemsArray')));


})

1 个答案:

答案 0 :(得分:1)

ng-click上的<button>ng-submit上的<form>都被触发,因此,您看到相同的数据被添加两次。您可以通过在第一个按钮上添加type="button"属性来修复它。

检查documentation - type属性的默认值为submit,因此,clicksubmit事件都被触发。