https://groups.google.com/forum/#!msg/angular/hVrkvaHGOfc/idEaEctreMYJ
来自Powel:
in fact $provide.provider,$provide.factory and $provide.service are
more or less the same thing in the sense that all of them are
blueprints / instructions for creating object instances (those
instances are then ready to be injected into collaborators).$provide.provider is the most spohisticated method of registering
blueprints,it allows you to have a complex creation function and
configuration options.$provide.factory is a simplified version of $provide.provider when you
don’t need to support configuration options but still want to have a
more sophisticated creation logic.$provide.service is for cases where the whole creation logic boils
down to invoking a constructor function.So,depending on the complexity of your construction logic you would
choose one of $provide.provider,$provide.factory and $provide.service
but in the end what you are going to get is a new instance.
这是附带的小提琴演示(从线程):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()]; }
原文地址:https://www.jb51.cc/angularjs/145292.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。