E
E
Ekaterina2014-11-14 09:46:24
Angular
Ekaterina, 2014-11-14 09:46:24

What is the best way to save service state between angular modules?

There are 2 modules that use the 3rd module. In module 3, there are services that must maintain state over time.
You can stupidly save to the global area (window), but maybe there is an angular-way?
jsfiddle.net/27xo9t5m/1

Answer the question

In order to leave comments, you need to log in

1 answer(s)
_
_ _, 2014-11-14
@AMar4enko

The first time you try to resolve a service somewhere in your application, it is instantiated and lives until the application terminates.

angular.module('my-module', [])
  .service('usefulService', function(){
      var usefulVar = 0;
      this.doSomethingUseful = function(){ userfulVar += 1; return usefulVar; };
      this.getUsefulVar = function(){ return usefulVar; } 
  });

When you inject a usefulService into a controller, the service's constructor function will execute once, and that service instance will be used throughout the application afterwards.
Therefore, such a service will store its state globally for the entire application.
If this is not the answer to your question, then you have formulated it incorrectly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question