Sunday, September 2, 2012

AngularJS: Using Services for Global State

In Javascript, global variables are sometimes needed to store state information that needs to be shared by multiple elements on a page. However, with global variables, you'll always run the chance of conflicting with another variable declared with the same name by another component, and obviously violates the principle of encapsulation.

With AngularJS, it's possible to use the services feature to achieve the same thing, but with encapsulation. This is because services are a singleton, meaning the same instance of an object can be shared across all AngularJS code in the same app.

Example:

angular.module('someModule', [ ]).factory(
'AppState',
function() {
function SomeClass(){
// what you want as global variables and functions to access them here
}
var instance = new SomeClass();
return instance;
});

No comments:

Post a Comment