javascript—数据是否可以使用$scope从一个视图持久化到另一个视图?

w8f9ii69  于 2021-09-29  发布在  Java
关注(0)|答案(0)|浏览(296)

我有一个表单可以从位于view1中的用户处获取数据:

<form ng-submit="addClient()">
      Numero client : <br>
      <input type="text" placeholder="Numero client" ng-model="newclient.numClient" /><br><br>
      Rue : <br>
      <input type="text"   placeholder="Rue" ng-model="newclient.rue" /><br><br>
      Numero de rue : <br>
      <input type="text"  placeholder="Numero de rue" ng-model="newclient.numRue" /><br><br>
      Code postal : <br>
      <input type="text"   placeholder="Code postal" ng-model="newclient.codePostal" /><br><br>
      Localite : <br>
      <input type="text"   placeholder="Localite" ng-model="newclient.localite"  /><br><br>
      <input type="submit"  value="Enregister">
    </form>

我试图在另一个视图中显示我获得的数据:view2:

<div class="listClients" >
    <h1>Liste des clients :</h1>

      <ul>
        <li ng-repeat="x in clients">
          <h3>{{x.numClient}} - {{x.rue}}</h3>
        </li>
      </ul>
  </div>

使用本地存储器存储数据。app.js:mycontroller:

myApp.controller('myController',function($scope, $location, $http){

  //initialize clients with 1 client : clients is an array now
  $http.get("data/clients.json").then(function(response){
      $scope.clients = response.data;
  });

  $scope.addClient = function(){

    $scope.client = {
       numClient: parseInt($scope.newclient.numClient),
       rue: $scope.newclient.rue,
       numRue: parseInt($scope.newclient.numRue),
       codePostal: parseInt($scope.newclient.codePostal),
       localite: $scope.newclient.localite
   };
   //saves the registered client to local storage : localStorage.setItem(key,value);
   localStorage.setItem($scope.client.numClient,angular.toJson($scope.client));

   //saves from local storage to $scope.clients
   for(var i =0; i<localStorage.length; i++){
     $scope.clients.push(angular.fromJson(localStorage.getItem(localStorage.key(i))));
   };

   console.log($scope.clients); // log 1: this log here works as expected

   //reseting newclient for future use
   $scope.newclient.numClient = "";
   $scope.newclient.rue = "";
   $scope.newclient.numRue = "";
   $scope.newclient.codePostal = "";
   $scope.newclient.localite = "";

  };

});

数据保存在阵列客户端中。我尝试在同一视图中使用ng repeat显示它:view1,它可以工作,直到我刷新页面或尝试从view2显示数组:数据从数组中消失。因为我使用的是localstorage,所以我仍然可以通过控制台记录它,但它并不有用。
有没有办法使客户机数组持久化,以便我可以从另一个视图显示它?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题