angularjs – 在创建服务方法时,module.service和module.factory
我不知道什么是最佳实践和我应该使用。
下面两种方法有什么区别? module.service(..); 和 module.factory(..);
有一个伟大的谷歌集团帖子关于这一点从Pawel Kozlowski:
https://groups.google.com/forum/#!msg/angular/hVrkvaHGOfc/idEaEctreMYJ 来自Powel:
这是附带的小提琴演示(从线程):http://jsfiddle.net/pkozlowski_opensource/PxdSP/14/ 而代码: 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() { 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()]; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |