Should a controller call a service or factory?
This question already has an answer here:
Use factory
if object definition syntax is preferable
app.factory('factory', function () {
...
return {
value: '...'
};
});
or it returns something that is not an object for some reason.
Use service
if this
syntax is preferable
app.service('service', function () {
this.value = '...';
});
or it should return an object created with new
from another constructor, eg
app.factory('factory', function () {
return new someConstructor();
});
vs.
app.service('service', someConstructor);
A good use case for service
is that you can seamlessly refactor existing controllers with controllerAs
syntax to inherit from common service, in this case no this
statements replacement is required, as shown here:
app.service('parentControllerService', function () {
this.value = '...';
});
app.controller('MainController', function (parentControllerService) {
angular.extend(this, parentControllerService);
});
app.controller('ChildController', function (parentControllerService) {
angular.extend(this, parentControllerService);
this.value = '!!!';
});
链接地址: http://www.djcxy.com/p/77888.html
上一篇: 在Angular控制器中使用下划线
下一篇: 控制器是否应该拨打服务或工厂?