??
供应者(Providers)
变量方式(Value Recipe)
var myApp = angular.module('myApp',[]);
myApp.value('clientId','a12345654321x');
myApp.controller('DemoController',['clientId',function DemoController(clientId) {
this.clientId = clientId;
}]);
<html ng-app="myApp">
<body ng-controller="DemoController as demo">
Client ID: {{demo.clientId}}
</body>
</html>
工厂方式(Factory Recipe)
myApp.factory('clientId',0);" data-mce-style="color: #000000;"> clientIdFactory() {
return 'a12345654321x';
});
myApp.factory('apiToken',0);" data-mce-style="color: #000000;"> apiTokenFactory(clientId) {
var encrypt = (data1,data2) {
// NSA-proof encryption algorithm:
return (data1 + ':' + data2).toUpperCase();
};
var secret = window.localStorage.getItem('myApp.secret');
var apiToken = encrypt(clientId,secret);
return apiToken;
}]);
服务方式(Service Recipe)
UnicornLauncher(apiToken) {
this.launchedCount = 0;
this.launch = () {
make a request to the remote api and include the apiToken
...
this.launchedCount++;
}
}
myApp.factory('unicornLauncher',["apiToken",0);" data-mce-style="color: #000000;">(apiToken) {
return new UnicornLauncher(apiToken);
}]);
myApp.service('unicornLauncher',UnicornLauncher]);
供应者方式(Provider Recipe)
myApp.provider('unicornLauncher',0);" data-mce-style="color: #000000;"> UnicornLauncherProvider() {
var useTinfoilShielding = falsethis.useTinfoilShielding = (value) {
useTinfoilShielding = !!value;
};
this.$get = ["apiToken",0);" data-mce-style="color: #000000;"> unicornLauncherFactory(apiToken) {
let's assume that the UnicornLauncher constructor was also changed to
// accept and use the useTinfoilShielding argument
UnicornLauncher(apiToken,useTinfoilShielding);
}];
});
myApp.config(["unicornLauncherProvider",0);" data-mce-style="color: #000000;">(unicornLauncherProvider) {
unicornLauncherProvider.useTinfoilShielding(true);
}]);
常量方式(Constant Recipe)
myApp.config(['unicornLauncherProvider','planetName',0);" data-mce-style="color: #000000;">(unicornLauncherProvider,planetName) {
unicornLauncherProvider.useTinfoilShielding();
unicornLauncherProvider.stampText(planetName);
}]);
DemoController(clientId,planetName) {
clientId;
this.planetName = planetName;
}]);
<html ng-app="myApp">
<body ng-controller="DemoController as demo">
Client ID: {{demo.clientId}}
<br>
Planet Name: {{demo.planetName}}
</body>
</html>
特殊目的对象(Special Purpose Objects)
myApp.directive('myPlanet',['planetName',0);" data-mce-style="color: #000000;"> myPlanetDirectiveFactory(planetName) {
directive definition object
{
restrict: 'E'function($scope,$element) { $element.text('Planet: ' + planetName); }
}
}]);
<html ng-app="myApp">
<body>
<my-planet></my-planet>
</body>
</html>
DemoController(clientId) {
clientId;
}]);
结论(Conclusion)