app.controller(‘myProvider’, function($scope, myProvider){$scope.artist = myProvider.getArtist();$scope.data.thingFromConfig = myProvider.thingOnConfig;});
app.provider(‘myProvider’, function(){//Only the next two lines are available in the app.config()this._artist = ‘’;this.thingFromConfig = ‘’;this.$get = function(){var that = this;return {getArtist: function(){return that._artist;},thingOnConfig: that.thingFromConfig}}});
app.config(function(myProviderProvider){myProviderProvider.thingFromConfig = ‘This was set in config’;});
var Person = function(name, age){this.name = name;this.age = age;}Person.prototype.sayName = function(){alert(‘My name is ‘ + this.name);}var tyler = new Person(‘Tyler’, 23);tyler.sayName(); //alerts ‘My name is Tyler’
var Person = function(name, age){//The below line creates an object(obj) that will delegate to the person’s prototype on failed lookups.//var obj = Object.create(Person.prototype);
//The line directly below this sets ‘this’ to the newly created object//this = obj;
this.name = name;this.age = age;
//return this;}
app.config(function(myProviderProvider){//Providers are the only service you can pass into app.configmyProviderProvider.thingFromConfig = 'This sentence was set in app.config. Providers are the only service that can be passed into config. Check out the code to see how it works';});
var app= angular.module('myApp', []);//creating service using factory methodapp.factory('factoryPattern',function(){var data={'firstName':'Tom','lastName':' Cruise',greet: function(){console.log('hello!' + this.firstName + this.lastName);}};
//Now all the properties and methods of data object will be available in our service objectreturn data;});
//Creating a service using the service methodvar app= angular.module('myApp', []);app.service('servicePattern',function(){this.firstName ='James';this.lastName =' Bond';this.greet = function(){console.log('My Name is '+ this.firstName + this.lastName);};});
/*step1:define a service */app.provider('service',function serviceProviderConstructor(){});
/*step2:configure the service */app.config(function configureService(serviceProvider){});
提供者语法在内部如何工作?
1. Provider对象是使用我们在提供者函数中定义的构造函数创建的。
var serviceProvider = new serviceProviderConstructor();
var app= angular.module('myApp', []);app.provider('providerPattern',function providerConstructor(){//this function works as constructor function for providerthis.firstName = 'Arnold ';this.lastName = ' Schwarzenegger' ;this.greetMessage = ' Welcome, This is default Greeting Message' ;//adding some method which we can call in app.config() functionthis.setGreetMsg = function(msg){if(msg){this.greetMessage = msg ;}};
//We can also add a method which can change firstName and lastNamethis.$get = function(){var firstName = this.firstName;var lastName = this.lastName ;var greetMessage = this.greetMessage;var data={greet: function(){console.log('hello, ' + firstName + lastName+'! '+ greetMessage);}};return data ;};});
app.config(function(providerPatternProvider){providerPatternProvider.setGreetMsg(' How do you do ?');});
<div ng-controller="mainCtrl as main"><h1>\{\{main.title}}*</h1><h2>\{\{main.strapline}}</h2><p>Earn \{\{main.earn}} per click</p><p>You've earned \{\{main.earned}} by clicking!</p><button ng-click="main.handleClick()">Click me to earn</button><small>* Not actual money</small></div>
应用程序
var app = angular.module('angularProviders', []);
// A CONSTANT is not going to changeapp.constant('range', 100);
// A VALUE could change, but probably / typically doesn'tapp.value('title', 'Earn money by clicking');app.value('strapline', 'Adventures in ng Providers');
// A simple FACTORY allows us to compute a value @ runtime.// Furthermore, it can have other dependencies injected into it such// as our range constant.app.factory('random', function randomFactory(range) {// Get a random number within the range defined in our CONSTANTreturn Math.random() * range;});
// A PROVIDER, must return a custom type which implements the functionality// provided by our service (see what I did there?).// Here we define the constructor for the custom type the PROVIDER below will// instantiate and return.var Money = function(locale) {
// Depending on locale string set during config phase, we'll// use different symbols and positioning for any values we// need to display as currencythis.settings = {uk: {front: true,currency: '£',thousand: ',',decimal: '.'},eu: {front: false,currency: '€',thousand: '.',decimal: ','}};
this.locale = locale;};
// Return a monetary value with currency symbol and placement, and decimal// and thousand delimiters according to the locale set in the config phase.Money.prototype.convertValue = function(value) {
var settings = this.settings[this.locale],decimalIndex, converted;
converted = this.addThousandSeparator(value.toFixed(2), settings.thousand);
decimalIndex = converted.length - 3;
converted = converted.substr(0, decimalIndex) +settings.decimal +converted.substr(decimalIndex + 1);
converted = settings.front ?settings.currency + converted :converted + settings.currency;
return converted;};
// Add supplied thousand separator to supplied valueMoney.prototype.addThousandSeparator = function(value, symbol) {return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, symbol);};
// PROVIDER is the core recipe type - VALUE, CONSTANT, SERVICE & FACTORY// are all effectively syntactic sugar built on top of the PROVIDER construct// One of the advantages of the PROVIDER is that we can configure it before the// application starts (see config below).app.provider('money', function MoneyProvider() {
var locale;
// Function called by the config to set up the providerthis.setLocale = function(value) {locale = value;};
// All providers need to implement a $get method which returns// an instance of the custom class which constitutes the servicethis.$get = function moneyFactory() {return new Money(locale);};});
// We can configure a PROVIDER on application initialisation.app.config(['moneyProvider', function(moneyProvider) {moneyProvider.setLocale('uk');//moneyProvider.setLocale('eu');}]);
// The ubiquitous controllerapp.controller('mainCtrl', function($scope, title, strapline, random, money) {
// Plain old VALUE(s)this.title = title;this.strapline = strapline;
this.count = 0;
// Compute values using our money providerthis.earn = money.convertValue(random); // random is computed @ runtimethis.earned = money.convertValue(0);
this.handleClick = function() {this.count ++;this.earned = money.convertValue(random * this.count);};});
app.factory('MyFactory', function() {var serviceObj = {};//creating an object with methods/functions or variablesserviceObj.myFunction = function() {//TO DO:};//return that objectreturn serviceObj;});
app.provider('configurableService', function() {var name = '';//this method can be be available at configuration time inside app.config.this.setName = function(newName) {name = newName;};this.$get = function() {var getName = function() {return name;};return {getName: getName //exposed object to where it gets injected.};};});
<script>angular.module('app', []).factory('CarFactory', function() {
/*** BroilerPlate Object Instance Factory Definition / Example*/this.Car = function() {
// initialize instance propertiesangular.extend(this, {color : null,numberOfDoors : null,hasFancyRadio : null,hasLeatherSeats : null});
// generic setter (with optional default value)this.set = function(key, value, defaultValue, allowUndefined) {
// by default,if (typeof allowUndefined === 'undefined') {// we don't allow setter to accept "undefined" as a valueallowUndefined = false;}// if we do not allow undefined values, and..if (!allowUndefined) {// if an undefined value was passed inif (value === undefined) {// and a default value was specifiedif (defaultValue !== undefined) {// use the specified default valuevalue = defaultValue;} else {// otherwise use the class.prototype.defaults valuevalue = this.defaults[key];} // end if/else} // end if} // end if
// updatethis[key] = value;
// return reference to this object (fluent)return this;
}; // end this.set()
}; // end this.Car class definition
// instance properties default valuesthis.Car.prototype.defaults = {color: 'yellow',numberOfDoors: 2,hasLeatherSeats: null,hasFancyRadio: false};
// instance factory method / constructorthis.Car.prototype.instance = function(params) {return newthis.constructor().set('color', params.color).set('numberOfDoors', params.numberOfDoors).set('hasFancyRadio', params.hasFancyRadio).set('hasLeatherSeats', params.hasLeatherSeats);};
return new this.Car();
}) // end Factory Definition.controller('testCtrl', function($scope, CarFactory) {
window.testCtrl = $scope;
// first car, is red, uses class default for:// numberOfDoors, and hasLeatherSeats$scope.car1 = CarFactory.instance({color: 'red'});
// second car, is blue, has 3 doors,// uses class default for hasLeatherSeats$scope.car2 = CarFactory.instance({color: 'blue',numberOfDoors: 3});// third car, has 4 doors, uses class default for// color and hasLeatherSeats$scope.car3 = CarFactory.instance({numberOfDoors: 4});// sets an undefined variable for 'hasFancyRadio',// explicitly defines "true" as default when value is undefined$scope.hasFancyRadio = undefined;$scope.car3.set('hasFancyRadio', $scope.hasFancyRadio, true);
// fourth car, purple, 4 doors,// uses class default for hasLeatherSeats$scope.car4 = CarFactory.instance({color: 'purple',numberOfDoors: 4});// and then explicitly sets hasLeatherSeats to undefined$scope.hasLeatherSeats = undefined;$scope.car4.set('hasLeatherSeats', $scope.hasLeatherSeats, undefined, true);
// in console, type window.testCtrl to see the resulting objects
});</script>
<html><head><title></title><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js" ></script><script type="text/javascript" src="t03.js"></script></head><body ng-app="app"><div ng-controller="emp"><div>Value of a is \{\{a}},but you can change<input type=text ng-model="a" /> <br>
Value of b is \{\{b}},but you can change<input type=text ng-model="b" /> <br>
</div>Sum = \{\{sum}}<br><button ng-click="doSum()">Calculate</button></div></body></html>
var app = angular.module('FactoryExample',[]);var factoryController = app.controller('FactoryController', FactoryController);var factoryExampleOne = app.factory('NameOfTheFactoryOne', NameOfTheFactoryOne);var factoryExampleTwo = app.factory('NameOfTheFactoryTwo', NameOfTheFactoryTwo);
//first implementation where it returns a functionfunction NameOfTheFactoryOne(){var factory = function(){return new SomeService();}return factory;}
//second implementation where an object literal would be returnedfunction NameOfTheFactoryTwo(){var factory = {getSomeService : function(){return new SomeService();}};return factory;}
现在在控制器中使用上述两个:
var factoryOne = NameOfTheFactoryOne() //since it returns a functionfactoryOne.someMethod();
var factoryTwo = NameOfTheFactoryTwo.getSomeService(); //accessing the objectfactoryTwo.someMethod();