Angular Services
First define the service (in this case it uses the factory pattern):
.factory('dataService', function() {
var dataObject = {};
var service = {
// define the getter method
get data() {
return dataObject;
},
// define the setter method
set data(value) {
dataObject = value || {};
}
};
// return the "service" object to expose the getter/setter
return service;
})
Now you can use the service to share data between controllers:
.controller('controllerOne', function(dataService) {
// create a local reference to the dataService
this.dataService = dataService;
// create an object to store
var someObject = {
name: 'SomeObject',
value: 1
};
// store the object
this.dataService.data = someObject;
})
.controller('controllerTwo', function(dataService) {
// create a local reference to the dataService
this.dataService = dataService;
// this will automatically update with any changes to the shared data object
this.objectFromControllerOne = this.dataService.data;
})
create a Service
angular.module("app")
.service("counterService", function(){
var service = {
number: 0
};
return service;
});
use a service
angular.module("app")
// Custom services are injected just like Angular's built-in services
.controller("step1Controller", ['counterService', '$scope', function(counterService,
$scope) {
counterService.number++;
// bind to object (by reference), not to value, for automatic sync
$scope.counter = counterService;
})
In the template using this controller you'd then write:
// editable
<input ng-model="counter.number" />
or
// read-only
<span ng-bind="counter.number"></span>
Of course, in real code you would interact with the service using methods on the controller, which in turn delegate to the service. The example above simply increments the counter value each time the controller is used in a template.
Services in Angularjs are singletons:
Services are singleton objects that are instantiated only once per app (by the $injector) and lazy loaded (created only when necessary).