provider, factory和service都是寫(xiě)Angularjs的service中常用的關(guān)鍵字,很容易混淆,寫(xiě)了一個(gè)簡(jiǎn)單的例子顯示他們之間的區(qū)別: 分別用service,factory和provider定義三個(gè)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'; } }); 在頁(yè)面上留出三個(gè)占位符: <body ng-controller='outputCtrl'> <p>{{ output1 }}</p> <p>{{ output2 }}</p> <p>{{ output3 }}</p> </body> 寫(xiě)好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; }); 最后頁(yè)面的顯示結(jié)果為; 說(shuō)明: 注入service,相當(dāng)于注入service定義時(shí)的function實(shí)例。 注入factory,相當(dāng)于注入factory定義時(shí)的函數(shù)調(diào)用入口。 注入provider,相當(dāng)于注入provider內(nèi)$get定義的函數(shù)實(shí)例的調(diào)用。 |
|