在
referenceI读:
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.
但是用这个简单的代码似乎不是一个单例
'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; });
我有点困惑你能解释我什么事?
更新1
可能我不是在棚子里最锋利的工具
但是在@Khanh TO回复它会是一个更好
解释在参考它不是很清楚。
更新2
'use strict'; angular.module('animal',function(){ return { vocalization:'',vocalize : function () { console.log('vocalize: ' + this.vocalization); } } }); angular.module('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',Dog){ $scope.cat = Cat; $scope.dog = Dog; console.log($scope.cat); console.log($scope.dog); //$scope.cat = Cat; });
BOOM这是一个单身!
更新3
但如果你喜欢
'use strict'; angular.module('animal',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',Dog){ $scope.cat = Cat; $scope.dog = Dog; console.log($scope.cat); console.log($scope.dog); //$scope.cat = Cat; });
有用