问题:
As I understand it, when inside a factory I return an object that gets injected into a controller. 据我了解,当在工厂内部时,我返回一个被注入控制器的对象。 When inside a service I am dealing with the object using this and not returning anything. 在服务内部时,我使用this处理对象而不返回任何内容。
I was under the assumption that a service was always a singleton , and that a new factory object gets injected in every controller. 我假设服务总是单例 ,并且每个控制器都会注入一个新的工厂对象 。 However, as it turns out, a factory object is a singleton too? 然而,事实证明,工厂对象也是单身人士?
Example code to demonstrate: 用于演示的示例代码:
var factories = angular.module('app.factories', []);
var app = angular.module('app', ['ngResource', 'app.factories']);
factories.factory('User', function () {
return {
first: 'John',
last: 'Doe'
};
});
app.controller('ACtrl', function($scope, User) {
$scope.user = User;
});
app.controller('BCtrl', function($scope, User) {
$scope.user = User;
});
When changing user.first in ACtrl it turns out that user.first in BCtrl is also changed, eg User is a singleton? 当改变user.first在ACtrl事实证明, user.first在BCtrl也发生了变化,例如, User是单身?
My assumption was that a new instance was injected in a controller with a factory? 我的假设是在一个带有工厂的控制器中注入了一个新实例?
解决方案:
参考一: https://stackoom.com/question/vkBQ/对服务与工厂感到困惑参考二: https://oldbug.net/q/vkBQ/Confused-about-Service-vs-Factory
来源:oschina
链接:https://my.oschina.net/u/4438370/blog/4272382