我想获得从工厂到控制器的响应。但是当我从控制器调用工厂的功能时,则控制器不会等待其响应。并给出“未定义”。如何使控制器在angularjs中等待工厂响应?
这里是我的controller.js
app.controller('customerCommentsController',function($scope,$http,$stateParams,$sce,$timeout,Comments){
var commentsdata = '';
Comments.init(1,5);
$scope.total_comments = Comments.total();
console.log($scope.total_comments); //undefined
$scope.positive_comments = Comments.positive();
console.log($scope.positive_comments); //undefined
$scope.commentsdata = Comments.getcomments(1,30);
console.log($scope.commentsdata); //undefined
});
这里我调用init()方法,它从ajax获得响应,这需要一些时间来执行,但在它可以完成之前,另一个2语句(total()和positive()方法)在init方法。并且由于init方法未完成而未得到初始化。那为什么我变得没有定义。 和我调用不等待响应的getcomments方法时会出现同样的问题。
这里是我厂
app.factory("Comments",function($http,$timeout,$q){
var commentshtml = [];
var commentshtml1 = [];
return {
init : function(start,end) {
var request = $http({
method:"post",
url:"/comments.php",
data: {start:start,end:end},
headers: {'Content-Type' : 'application/x-www-form-urlencoded'}
});
request.success(function(data){
commentshtml = data;
});
},
total : function() {
return commentshtml.total_comment;
},
positive : function(){
return commentshtml.per_positive_comment;
},
getcomments : function(start,end) {
var promise = $http({
method:"post",
url:"/comments.php",
data: {start:start,end:end},
headers: {'Content-Type' : 'application/x-www-form-urlencoded'}
});
promise.success(function(data){
commentshtml1 = data.comments;
console.log(commentshtml1); //giving the object
return commentshtml1;
});
}
};
你应该使用延期对象(见下文伊格纳特的答案),或至少回调。 – pietro909