我有一个提供者:
AdviceList.provider('$adviceList',function(){
this.$get = function ($rootScope,$document,$compile,$http,$purr){
function AdviceList(){
$http.post('../sys/core/fetchTreatments.php').success(function(data,status){
this.treatments = data;
console.log(this.treatments); // the correct object
});
this.adviceCategories = [
// available in the controller
];
}
return{
AdviceList: function(){
return new AdviceList();
}
}
}
});
此外,我有这个控制器:
AdviceList.controller('AdviceListCtrl',function($scope,$adviceList){
var adv = $adviceList.AdviceList();
$scope.treatments = adv.treatments; // undefined
});
为什么控制器的$scope.treatments
保持未定义,但提供商内的this.treatments
是否正确填充?此外,我的控制器中还提供了adviceCategories
。
答案 0 :(得分:1)
你得到的电话本质上是异步的,所以当你尝试分配它们时,结果可能没有被填充。
所以这里
var adv = $adviceList.AdviceList();
$scope.treatments = adv.treatments; //The treatments would only get filled after the server call is over.
您需要以在成功回调中将其分配给scope属性的方式重写代码。
答案 1 :(得分:1)
我建议您简化代码
1)使用简单的角度工厂方法代替提供者
2)返回一个避免使用回调的承诺
AdviceList.service('adviceList', function ($http) {
return {
adviceList: function () {
return $http.post('../sys/core/fetchTreatments.php');
}
}
});
AdviceList.controller('AdviceListCtrl', function ($scope, $adviceList) {
adviceList.AdviceList().then(function (data) {
$scope.treatments = data //set value to data when data is recieved from server
});
});