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'; } });
在頁面上留出三個占位符:
<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; });
最后頁面的顯示結果為;
說明:
注入service,相當於注入service定義時的function實例。
注入factory,相當於注入factory定義時的函數調用入口。
注入provider,相當於注入provider內$get定義的函數實例的調用。