Are Angularjs services singleton?

Solution 1:

It's singleton, there is only one object, but is injected into many places. (objects are passed by reference to a method)

All your Animal are object pointers referring to the same animal object which is a function in your case. Your Cat and Dog are objects constructed by this function.

Solution 2:

Yes, service is singleton. The following code log only one "M" to console:

function M() { console.log('M'); }
function M1(m) { console.log(1); }
function M2(m) { console.log(2); }
angular.module('app', [])
.service('M', M)
.service('M1', ['M', M1])
.service('M2', ['M', M2])
.controller('MainCtrl',function(M1, M2){});

run it in jsbin

Solution 3:

Let me give an example about singletons in AngularJS. Lets assume that we have 2 controllers used in different part of our single page application:

myApp.controller('mainController', ['$scope', '$log', function($scope, $log) {

    $log.main = 'First Var';
    $log.log($log);

}]);

So now if we went to the page that is controlled via mainController controller, we will see this at the log:

enter image description here

As you see, the log object now contain my first variable.

Now here is my second controller:

myApp.controller('secondController', ['$scope', '$log', '$routeParams', function($scope, $log, $routeParams) {

    $log.secondVar = 'Second Var';
    $log.log($log);

}]);

So if you click on the second page that is controlled, you will see this:

enter image description here

Now get back to the first page:

enter image description here

What do you conclude about those 3 steps ?

Their is one $log object injected to the app. And as Tony Alicea said: This is a big memory save.

So this service, is called one time, and each time we are adding new variables and parameters to the same object and not adding different objects for different parameters.