我的控制器正在调用服务工厂,我看到工厂成功进行API调用并将结果返回给控制器,但是分配给控制器的模板未呈现结果。
工厂:
.factory("clubService", function($http,$q) {
var clubs= [] ;
function clubsAll() {
clubs = [] ;
setVars() ; // function to set baseUrl/headers, etc
var dataObj = [{"type":1,"userID":userData.user_ID}]
var req = {
method: 'POST',
url: baseUrl ,
headers: headers,
data: JSON.stringify(dataObj)
}
return $http(req)
.then(function(response){
clubs = response.data ;
return clubs ;
}).catch(function(err) {
errMgmt("services/apiCall",700,err.code+", "+err.msg) ;
});
}
return {
all: function() {
return clubsAll() ;
//return clubs ;
}
}) ;
控制器:
.controller('ClubCtrl', function($scope,$state,clubService) {
$scope.clubs = clubService.all() ;
console.log($scope.clubs) ; // 'clubs' is getting populated in console.
})
在我的HTML中
<div ng-if="clubs.length == 0">
<img ng-src="img/loader.gif">
</div>
<div ng-if="clubs.length > 0">
<div ng-repeat="club in clubs">
{{club.Name}}
</div>
</div>
但是我的HTML中没有任何内容得到渲染,引用clubs
的所有内容均未显示,ng-if仍被注释掉,没有ng-repeat显示。
答案 0 :(得分:2)
在clubService的clubsAll()方法中,当您声明此行时,实际上是在返回诺言
return $http(req)
.then(function(response){
clubs = response.data ;
return clubs ;
}).catch(function(err) {
errMgmt("services/apiCall",700,err.code+", "+err.msg) ;
});
该承诺可以被解决(成功)或被拒绝(错误),如果您想从该承诺中获取俱乐部数据,则需要 在promise成功回调(.then)上的控制器逻辑上链接
.controller('ClubCtrl', function($scope,$state,clubService) {
clubService.all().then(function(response){
$scope.clubs = response;
});
})
答案 1 :(得分:0)
我想通了,我需要等待诺言在控制器中返回。
.controller('ClubCtrl', function($scope,$state,clubService) {
clubService.all()
.then(function(response) {
$scope.clubs = response ;
console.log($scope.clubs) ; // 'clubs' is getting populated in console.
}) ;
})