(1)实例
1.在service.js中定义服务
var appServices = angular.module('appServices', ['ngResource']);
appServices.factory('reverse', [
function(){
return {
myFunc:function(input){
var res = "";
if(input!=null){
for(var i=input.length-1; i>=0; i--){
res += input.charAt(i);
}
}
return res;
}
};
}]);
2.在controller.js中添加服务依赖并调用
var appControllers = angular.module('appControllers', []);
appControllers.controller('IndexCtrl', ['$scope','reverse',
function($scope,reverse) {
$scope.data = reverse.myFunc("check");
}]);
(2)说明
1.定义服务格式
var appServices = angular.module('appServices', ['ngResource']);
appServices.factory('服务名称', [
function(){
return {
方法名称:function(方法参数){
return 方法返回值;
}
};
}]);
这么看可能有些不容易看懂,看个其他例子
var mainApp = angular.module("mainApp", []);
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b
}
return factory;
});
所以看出,实际上就是为了返回一个Object实例,其中包含了多个方法,所以需要返回{}
所以服务中的方法实际上就是Object中的一个方法而已
2.调用服务
必须要将service实例进行注入才能够进行调用
(3)其他定义方式
1.使用service方法
angular.module('myApp.services')
.service('User', function($http) { // injectables go here
var self = this; // Save reference
this.user = {};
this.backendUrl = "http://localhost:3000";
this.setName = function(newName) {
self.user['name'] = newName;
}
this.setEmail = function(newEmail) {
self.user['email'] = newEmail;
}
this.save = function() {
return $http.post(self.backendUrl + '/users', {
user: self.user
})
}
});
2.使用provider方法
angular.module('myApp.services')
.provider('User', function() {
this.backendUrl = "http://localhost:3000";
this.setBackendUrl = function(newUrl) {
if (url) this.backendUrl = newUrl;
}
this.$get = function($http) { // injectables go here
var self = this;
var service = {
user: {},
setName: function(newName) {
service.user['name'] = newName;
},
setEmail: function(newEmail) {
service.user['email'] = newEmail;
},
save: function() {
return $http.post(self.backendUrl + '/users', {
user: service.user
})
}
};
return service;
}
});