How to save saved data in angular route service even when updating?

So, I basically translate data between 2 pages in angular using $ route service and not using url parameters.

I get the data sent to the second page by the first page, but when I update the data of the second page, it gets lost!

How can I solve this, I can’t use the url parameters, since the data will have many text fields and will also have an array.

I already use the service for data transfer, but the service data is not saved after the update.

I do not want the database to be impractical. I just want this data to remain on the client machine.

+4
source share
2 answers

You can use localStorageto save data:

Plunker

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="angular.js@1.1.5" data-semver="1.1.5" src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
    <script src="https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js"></script>
    
    <script>
      angular.module('app', [
        'ngStorage'
      ]).
      
      controller('Ctrl', function(
        $scope,
        $localStorage
      ){
        $scope.$storage = $localStorage.$default({
          x: 42,
          y: 1
        });
      });
    </script>
  </head>

  <body ng-controller="Ctrl">
    <button ng-click="$storage.x = $storage.x + 1">{{$storage.x}}</button> + <button ng-click="$storage.y = $storage.y + 1">{{$storage.y}}</button> = {{$storage.x + $storage.y}}
  </body>

</html>
Run codeHide result
+1
source

Services are always the best way to store data between controllers. The service saves data through the application life cycle, so we can create a simple way:

DataCacheService

angular.module('dataPassingDemo').service('DataCacheService', DataCacheService);

function DataCacheService () {
  var self = this,
      _cache = {};

  self.get = get;
  self.set = set;

  function get (key) {
    if (angular.isDefined(key) && angular.isDefined(_cache[key])) {
      return _cache[key];
    }

    return false;
  }

  function set (key, value) {
    if (angular.isDefined(key)) {
      _cache[key] = value;
    }
}

Then, given the two controllers:

Controller 1

angular.module('dataPassingDemo').controller('Controller1', Controller1);

function Controller1 (DataCacheService) {
  var vm = this;

  vm.setName = setName;

  function setName (name) {
    DataCacheService.set('name', name);
  }
}

Controller 2

angular.module('dataPassingDemo').controller('Controller2', Controller2);

function Controller2 (DataCacheService) {
  var vm = this;

  vm.name = DataCacheService.get('name');
}

You can see that we can easily transfer data between two controllers.

You can get more information about services and factories from in this article .

0
source

Source: https://habr.com/ru/post/1629193/


All Articles