问题描述
我在 Angular.js
上做了很多工作,总的来说,我发现它是一个有趣且强大的框架.
I've been doing a lot of work on Angular.js
and overall I find it to be an interesting and powerful framework.
我知道已经有很多关于服务与工厂、提供者与价值的讨论,但我仍然对 Factory
是什么感到很困惑.
I know there have been a lot of discussions on Services vs. Factories vs. Providers vs. Values, but I am still pretty confused about what a Factory
is.
Factory 已在其他 StackOverflow 讨论中定义如下:
Factory has been defined in other StackOverflow discussions as the following:
工厂
语法:module.factory('factoryName', function);
结果:当将 factoryName 声明为可注入参数时,您将获得通过调用传递给模块的函数引用返回的值.工厂.
Syntax: module.factory( 'factoryName', function );
Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.
我觉得这个解释很难理解,它并没有增加我对工厂是什么的理解.
I find this explanation to be very difficult to grasp and it doesn't increase my understanding of what a factory is.
有没有人有任何解释或现实生活中的例子来分享 Factory
到底是什么以及为什么你应该使用它代替 Service
、Provider
,还是其他?
Would anyone have any explanations or real life examples to share about what exactly a Factory
is and why you should use it in lieu of a Service
, Provider
, or other?
service
持有对任何对象的引用.
factory
是一个函数,它返回任何对象
provider
是一个函数,它返回任何函数
-呸-
推荐答案
据我所知,它们几乎都是一样的.主要区别在于它们的复杂性.提供者在运行时是可配置的,工厂更健壮一点,服务是最简单的形式.
From what I understand they are all pretty much the same. The major differences are their complexities. Providers are configurable at runtime, factories are a little more robust, and services are the simplest form.
看看这个问题 AngularJS:服务 vs 提供者 vs 工厂
此外,此 gist 可能有助于理解细微差别.
Also this gist may be helpful in understanding the subtle differences.
来源:https://groups.google.com/forum/#!主题/角度/hVrkvaHGOfc
jsFiddle:http://jsfiddle.net/pkozlowski_opensource/PxdSP/14/
作者:Pawel Kozlowski
var myApp = angular.module('myApp', []);
//service style, probably the simplest one
myApp.service('helloWorldFromService', function() {
this.sayHello = function() {
return "Hello, World!";
};
});
//factory style, more involved but more sophisticated
myApp.factory('helloWorldFromFactory', function() {
return {
sayHello: function() {
return "Hello, World!";
}
};
});
//provider style, full blown, configurable version
myApp.provider('helloWorld', function() {
// In the provider function, you cannot inject any
// service or factory. This can only be done at the
// "$get" method.
this.name = 'Default';
this.$get = function() {
var name = this.name;
return {
sayHello: function() {
return "Hello, " + name + "!";
}
};
};
this.setName = function(name) {
this.name = name;
};
});
//hey, we can configure a provider!
myApp.config(function(helloWorldProvider){
helloWorldProvider.setName('World');
});
function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {
$scope.hellos = [
helloWorld.sayHello(),
helloWorldFromFactory.sayHello(),
helloWorldFromService.sayHello()];
}
这篇关于AngularJS:什么是工厂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!