provider, factory和service都是写AngularJS的service中常用的关键字,很容易混淆,写了一个简单的例子显示他们之间的区别:
分别用service,factory和provider定义三个service:
- var wtcModule = angular.module('wtc', []);
- wtcModule.service('testService',function(){
- this.lable = 'this is service';
- });
- wtcModule.factory('testFactory', function () {
- return{
- lable: function(){
- return 'this is factory';
- }
- }
- });
- wtcModule.provider('testProvider', function(){
- this.$get = function(){
- return 'this is provider';
- }
- });
var wtcModule = angular.module('wtc', []);
wtcModule.service('testService',function(){
this.lable = 'this is service';
});
wtcModule.factory('testFactory', function () {
return{
lable: function(){
return 'this is factory';
}
}
});
wtcModule.provider('testProvider', function(){
this.$get = function(){
return 'this is provider';
}
});
在页面上留出三个占位符:
- <body ng-controller='outputCtrl'>
- <p>{{ output1 }}</p>
- <p>{{ output2 }}</p>
- <p>{{ output3 }}</p>
- </body>
<body ng-controller='outputCtrl'>
<p>{{ output1 }}</p>
<p>{{ output2 }}</p>
<p>{{ output3 }}</p>
</body>
写好outputCtrl:
- var wtcModule = angular.module('wtc');
- wtcModule.controller('outputCtrl', function($scope,testService, testFactory, testProvider){
- $scope.output1 = testService.lable;
- $scope.output2 = testFactory.lable();
- $scope.output3 = testProvider;
- });
var wtcModule = angular.module('wtc');
wtcModule.controller('outputCtrl', function($scope,testService, testFactory, testProvider){
$scope.output1 = testService.lable;
$scope.output2 = testFactory.lable();
$scope.output3 = testProvider;
});
最后页面的显示结果为;
说明:
注入service,相当于注入service定义时的function实例。
注入factory,相当于注入factory定义时的函数调用入口。
注入provider,相当于注入provider内$get定义的函数实例的调用。
转自:http://blog.csdn.net/u012841667/article/details/52749996