AngularJs:在angularJs中本地保存数据

时间:2016-05-31 08:26:55

标签: angularjs

我有一个项目正在处理一个购物清单,并且正在以这样一种方式制作,即用户输入他想要添加的项目,并且每当他添加它时,显示他已经为某个特定产品添加了产品而不是忘记他拥有能够从列表中删除任何产品。但是,当我从未重新加载页面时,它显示为空,即使我之前已经添加了一些项目..这是代码

var app =  angular.module("shoppingList",[]);
      app.controller("myCtrl",function($scope){
          $scope.goods = []

          var taskData = localStorage()


          $scope.addItem = function(){
              $scope.errorText = "";
              if(!$scope.addNew){return;}
              if($scope.goods.indexOf($scope.addNew) == -1){
                       $scope.goods.push($scope.addNew);  
              }else{
                  $scope.errorText = "The Item is already in your shopping list"
              }

          };

          $scope.removeItem = function(x){
              $scope.errorText = ""
              $scope.goods.splice(x,1);
          }

      })

1 个答案:

答案 0 :(得分:0)

在您的应用中使用https://github.com/gsklee/ngStorage是个好主意,因为它会让您以有角度的方式使用localstorage。所以用ngStorage重写代码:

 var app =  angular.module("shoppingList",['ngStorage']);
  app.controller("myCtrl",function($scope,$localStorage){
      $scope.goods = $localStorage.goods || [];

      var taskData = localStorage()


      $scope.addItem = function(){
          $scope.errorText = "";
          if(!$scope.addNew){return;}
          if($scope.goods.indexOf($scope.addNew) == -1){
                   $scope.goods.push($scope.addNew);  
                   $localStorage.goods.push($scope.addNew);
          }else{
              $scope.errorText = "The Item is already in your shopping list"
          }

      };

      $scope.removeItem = function(x){
          $scope.errorText = ""
          $scope.goods.splice(x,1);
          $localStorage.goods.splice(x,1);
      }

  })

希望这对你有用