A Service in AngularJS is implemented as a singleton. As such it can be used in multiple controllers and can be the means to share objects and values across controllers given that each controller has an independent $scope.
A service is defined by calling the Module.service function and passing a service name and a function where we add variables and functions.
var myApp = angular.module('myApp', ['ngRoute']); myApp.service('nameService', function() { var self = this; this.name = 'Some Name'; this.someFunction = function() { ... use self variable here return someValue; }; });
To make the service accessible to controllers, it needs to be injected like any other service. If the service contains a value that needs to be changeable from multiple controllers, there are two things that we need to do in each controller:
- We need to assign the service value to a scope variable to make it accessible in the view.
- We need to make the scope observe the scope variable by calling the $watch function, which takes the variable name and a function. Inside this function we will update the service variable.
If we perform those two tasks we will insure the controllers will be sharing a value using the service as the intermediary.
myApp.controller('mainController', ['$scope', '$log', 'nameService', function($scope, $log, nameService) { $scope.name = nameService.name; $scope.$watch('name', function() { nameService.name = $scope.name; }); $log.log(nameService.name); }]);