这是我的观点(抱歉长变量和函数名称):
<tr ng-repeat="passation in passations " >
<td ng-init=" passation.stats_quota_campagnes = get_stats_quota_campagnes(passation)">{{passation.stats_quota_campagnes}}</div></td>
</tr>
这是我的angularjs函数,它应该返回结果:
$scope.get_stats_quota_campagnes = function(passation){
var defer = $q.defer();
$http.post('backend/backend.php?action=stats_quota_campagnes',{'id_passation':passation.id_passation})
.success(function(data){
console.log(data);
defer.resolve(data);
});
return defer.promise;
}
console.log(数据);显示这一点,'即时从PHP后端获取正确的数据:
Object { 0: "401", Quota: "401" }
但我已经尝试了很多东西,但完全无法将Quota值纳入我的视野! defer.promise变量总是空的我不明白为什么。我该怎么办?
在我看来,实际上就是这样:
{}
而不是值,而console.log显示它正在工作,正确的变量来自$ http,但视图不会更新。我听说过$ apply(),但不知道如何使用它。
答案 0 :(得分:0)
您只能在then
回调:
somePromise.then(function(value) {
console.log(value)
})
在您的情况下,您可以执行以下操作:
$scope.get_stats_quota_campagnes = function(passation){
var defer = $q.defer();
$http.post('backend/backend.php?action=stats_quota_campagnes',{'id_passation':passation.id_passation})
.success(function(data){
console.log(data);
$scope.data = data;
});
}
然后您可以在模板中访问$scope.data
答案 1 :(得分:0)
您无需对您的承诺执行任何操作,只需将数据分配给.then
回调中的变量:
$scope.get_stats_quota_campagnes = function(passation){
$http.post('backend/backend.php?action=stats_quota_campagnes',{'id_passation':passation.id_passation})
.success(function(data){
console.log(data);
passation.stats_quota_campagnes = data;
});
}
在你看来:
<tr ng-repeat="passation in passations">
<td ng-init="get_stats_quota_campagnes(passation)">
{{passation.stats_quota_campagnes}}
</td>
</tr>
答案 2 :(得分:0)
这不是它的工作原理。如果要初始化DO
范围,则必须在控制器中调用服务,然后将结果分配给范围。
e.g。
passation.stats_quota_campagnes
然后在视图中
angular.module('app')
.controller('myController', ['$scope', 'myService', function ($scope, myService) {
//...some other code in your controller.
$scope.passation.stats_quota_campagnes = [];
$scope.get_stats_quota_campagnes = function (passation, index) {
myService(passation).then(successCallback, failCallback);
function successCallback(response) {
$scope.passation[index].stats_quota_campagnes = response;
};
function failCallback(response) {
//Do whatever you have to do.
}
};
//This requires you have passation array initialized.
angular.forEach(passation, function(val,index) {
$scope.get_stats_quota_campagnes(val,index);
});
}])
.service('myService', ['$http', '$q', function ($http, $q) {
return function (passation) {
var defer = $q.defer();
$http.post('backend/backend.php?action=stats_quota_campagnes', {
'id_passation': passation.id_passation
})
.success(function (data) {
console.log(data);
defer.resolve(data);
});
return defer.promise;
}
}])