一个简单的例子,控制层:
.controller('publishController',['$scope','publishService', function($scope,publishService){
publishService.getData().then(
function(answer){
$scope.data = answer.data;
console.info(answer);
},
function(error){
$scope.error = error;
}
); }])
服务层:
app.service('publishService',['$http','$q',function($http,$q){
return {
getData:function(){
var deferred = $q.defer();
var promise = $http.post(url);
promise.then(
// 通讯成功的处理
function(answer){
//在这里可以对返回的数据集做一定的处理,再交由controller进行处理
answer.status = true;
deferred.resolve(answer);
},
// 通讯失败的处理
function(error){
// 可以先对失败的数据集做处理,再交由controller进行处理
error.status = false;
deferred.reject(error);
});
//返回promise对象,交由controller继续处理成功、失败的业务回调
return deferred.promise;
}
}
}]);
app:
var app = angular.module("myApp", ['ngAnimate','ngRoute']);