var app=angular.module('myApp',[]);
app.factory('UserInfoService',['$http','$q',function($http,$q){
return{
query:function(){
var defer=$q.defer(); //声明延后执行
$http({method:'GET',url:'../json/students.json'}).
success(function(data,status,headers,config){
defer.resolve(data); //声明执行成功
if(config.showLog){
console.log('promise: UserInfoService success');
}
}).
error(function(data,status,headers,config){
defer.reject(data); //声明执行失败
});
return defer.promise; //返回承诺,返回获取数据的API
}
}
}]);
// config.showLog=true;
app.controller('MainCtrl',['$scope','UserInfoService',function($scope,UserInfoService){
var promise = UserInfoService.query(); //同步调用,获取承诺接口
promise.then(function(data){
$scope.user=data; //调用承诺接口resolove()
if(config.showLog){
console.log('promise:成功--MainCtrl ...');
console.log('\n');
}
},function(data){
$scope.user={error:'数据不存在。。。'}; //调用承诺接口reject();
});
}]);
angular.bootstrap(document,['myApp'])