In the referenceI read:
Lastly, it is important to realize that all Angular services are application singletons. This means that there is only one instance of a given service per injector.
but with this simple code seems not to be a singleton
'use strict';
angular.module('animal', [])
.factory('Animal',function(){
return function(vocalization){
return {
vocalization:vocalization,
vocalize : function () {
console.log('vocalize: ' + this.vocalization);
}
}
}
});
angular.module('app', ['animal'])
.factory('Dog', function (Animal) {
return Animal('bark bark!');
})
.factory('Cat', function (Animal) {
return Animal('meeeooooow');
})
.controller('MainCtrl',function($scope,Cat,Dog){
$scope.cat = Cat;
$scope.dog = Dog;
console.log($scope.cat);
console.log($scope.dog);
//$scope.cat = Cat;
});
I'm a little confused can you explain me what's the matter ?
UPDATE 1 May be I'm not the sharpest tool in the shed but afer the @Khanh TO reply it would be a better explanation in the reference it's not very clear.
UPDATE 2
'use strict';
angular.module('animal', [])
.factory('Animal',function(){
return {
vocalization:'',
vocalize : function () {
console.log('vocalize: ' + this.vocalization);
}
}
});
angular.module('dog', ['animal'])
.factory('Dog', function (Animal) {
Animal.vocalization = 'bark bark!';
Animal.color = 'red';
return Animal;
});
angular.module('cat', ['animal'])
.factory('Cat', function (Animal) {
Animal.vocalization = 'meowwww';
Animal.color = 'white';
return Animal;
});
angular.module('app', ['dog','cat'])
.controller('MainCtrl',function($scope,Cat,Dog){
$scope.cat = Cat;
$scope.dog = Dog;
console.log($scope.cat);
console.log($scope.dog);
//$scope.cat = Cat;
});
BOOM it's a singleton !
UPDATE 3
But if you do like
'use strict';
angular.module('animal', [])
.factory('Animal',function(){
return function(vocalization){
return {
vocalization:vocalization,
vocalize : function () {
console.log('vocalize: ' + this.vocalization);
}
}
}
});
angular.module('app', ['animal'])
.factory('Dog', function (Animal) {
function ngDog(){
this.prop = 'my prop 1';
this.myMethod = function(){
console.log('test 1');
}
}
return angular.extend(Animal('bark bark!'), new ngDog());
})
.factory('Cat', function (Animal) {
function ngCat(){
this.prop = 'my prop 2';
this.myMethod = function(){
console.log('test 2');
}
}
return angular.extend(Animal('meooow'), new ngCat());
})
.controller('MainCtrl',function($scope,Cat,Dog){
$scope.cat = Cat;
$scope.dog = Dog;
console.log($scope.cat);
console.log($scope.dog);
//$scope.cat = Cat;
});
it works