AngularJS Services - The singleton data and code sharing method

By: Varghese Chacko 2 years, 3 months ago

Angular JS logoAngular services are used to organize code across the application and are wired together using Dependancy Injection. Angular services are lazily instantiated, i.e, they are instantiated only when an application component depends on it.They are singletons, ie there will be only one instance exists for the app and the components depending on the service gets the reference to the service.

To use a service, we have to add it as a dependany on any component. Here is the famous example from angular documentation

module('myServiceModule', []).
 controller('MyController', ['$scope', 'notify', function($scope, notify) {
   $scope.callNotify = function(msg) {
factory('notify', ['$window', function(win) {
   var msgs = [];
   return function(msg) {
     if (msgs.length === 3) {
       msgs = [];

Here we have an app named myServiceModule and we define a service named notify, which is created as a factory method in the app using the factory API of Angular. First we define an array named msgs to save the messages and then a function that is being returned from service. Then we push the received message to the array and alert the array when it has 3 messages.

In the controller, we inject the dependancy for the service and the function callNotify invokes the service. HTML for this code could be

<div id="simple" ng-controller="MyController">
  <p>Let's try this simple notify service, injected into the controller...</p>
  <input ng-init="message='test'" ng-model="message" >
  <button ng-click="callNotify(message);">NOTIFY</button>
  <p>(you have to click 3 times to see an alert)</p>

When you click the button, it invokes and alerts when the count of click is three. Since the service is singleton, every time, same instance is invoked and the data pushed to the variable msg ispersistant.

A service can return a javascript object tohave multiple functions and variables exposed and could be used to share data between controllers and other services.

Let us talk!

We take the vision which comes from dreams and apply the magic of science and mathematics, adding the heritage of our profession and our knowledge to create a design.