Angular提供了三种服务:factory、service和provider。
下面的代码放入 /path/to/tomcat/webapp,
(1)Windows进入/path/to/tomcat/bin,运行startup.bat,如果配置了环境变量CATALINA_HOME,直接cmd执行startup.bat即可;
(2)Linux进入/path/to/tomcat/bin,执行./startup.sh。
输入url:localhost:8080/your_path/xxx.html即可运行。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>AngularJS 中的 factory、 service 和 provider</title>
<script src="js/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', []);
app.factory('MyFactory', function() {
// define result object of factory.
var result = {};
// add some property and method to the object
result.greeting = 'Hello from factory.';
// return the object;
return result;
});
app.service('MyService', function() {
this.greeting = 'Hello from service';
});
app.provider('MyProvider', function() {
// default name is 'anonymous';
var defaultName = 'anonymous';
var name = defaultName;
// setName can be called duaring module init
this.setName = function(newName) {
name = newName;
}
this.$get = function() {
var result = {};
result.greeting = 'Hello from provider';
result.name = name;
result.defaultName = defaultName;
return result;
}
})
app.controller('TestController', ['$scope', 'MyFactory', 'MyService', 'MyProvider', function($scope, myFactory, myService, myProvider) {
$scope.greetingFromFactory = myFactory.greeting;
$scope.greetingFromService = myService.greeting;
$scope.greetingFromProvider = myProvider.greeting;
$scope.defaultName = myProvider.defaultName;
$scope.name = myProvider.name
}]);
app.config(function(MyProviderProvider) {
MyProviderProvider.setName('Angularjs Provider');
});
</script>
</head>
<body ng-app="MyApp" ng-controller="TestController">
<p>greeting from factory: {{greetingFromFactory}}</p>
<p>greeting from service: {{greetingFromService}}</p>
<p>greeting from provider: {{greetingFromProvider}}</p>
<p>defaultName: {{defaultName}}, config to: {{name}}</p>
</body>
</html>