<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular.js"></script>
<div ng-controller="detail">
<input type="number" ng-model="x">
<input type="number" ng-model="y">
<button ng-click="add()">总和</button>
<br />
<label>{{z}}</label>
</div>
<script>
angular.module('app.service', [])
.config(['$provide',function($provide){
$provide.service('calc',[function(){
this.plusnum="";
this.add = function(x,y) {
this.plusnum+="+";
return x+y+this.plusnum;
}
}]);
}]);
angular.module('app', ['app.service'])
.controller('detail',['$scope','calc',function($scope,calc) {
angular.extend($scope,{
x:0,y:0,z:0
});
$scope.add=function(){
$scope.z=calc.add($scope.x,$scope.y);
}
}]);
angular.bootstrap(document, ['app']);
</script>
</html>
$scope加属性的时候切莫使用scope={x:0},会覆盖掉原来的对象,让功能失效, 因为是一个实例,所以每次调用服务plusnum都会存在上一次的
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular.js"></script>
<div ng-controller="detail">
<input type="number" ng-model="x">
<input type="number" ng-model="y">
<button ng-click="add()">总和</button>
<br />
<label>{{z}}</label>
</div>
<script>
angular.module('app.service', [])
.config(['$provide',function($provide){
$provide.factory('calc', [function(){
return {add :function(x,y) {
return x+y;
}
}
}]);
}]);
angular.module('app', ['app.service'])
.controller('detail',['$scope','calc',function($scope,calc) {
angular.extend($scope,{
x:0,y:0,z:0
});
$scope.add=function(){
$scope.z=calc.add($scope.x,$scope.y);
}
}]);
angular.bootstrap(document, ['app']);
</script>
</html>
用factory方法创建一个服务,需要返回值,否则就是undefined, 如果是方法使用的时候需要实例化或者直接返回一个对象,上面的例子是直接返回对象
angular.module('app.service', [])
.config(['$provide',function($provide){
$provide.service('test',['$http',function($http){
this.test = function() {
var config={
method:'jsonp',
url:'http://geoip.weather.com.cn/g/',
headers :{},
data :{a:'test'},
cache :false,
transformRequest:function(data, headersGetter),
transformResponse:function(data, headersGetter),
xsrfHeaderName:'',
xsrfCookieName :'',
withCredentials:true,
timeout :'1000',
responseType :'json',
};
$http(config);
.success(function(){}))
.error(function(){})
}
}]);
}]);
基本配置和ajax类似,也可以直接使用$http.get(url,config)这些来调用,其中主要区别是getJSON和jsonp的方法名称,以及几个不常用的方法$http.head$http.post$http.put$http.delete
- 其中xsrfHeaderName和xsrfCookieName、withCredentials主要用来跨域的时候验证,不在angularjs范围内 具体内容可以参考HTTP access control
- 其中transformRequest和transformResponse的参数是一个方法或者一个数组的方法