我有一个提供商:
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();
}
}
}
});
此外,我有这个 Controller :
AdviceList.controller('AdviceListCtrl',function($scope,$adviceList){
var adv = $adviceList.AdviceList();
$scope.treatments = adv.treatments; // undefined
});
为什么 Controller 的 $scope.treatments
保持未定义状态,而提供程序内部的 this.treatments
却被正确填充?此外,adviceCategories
在我的 Controller 中可用。
最佳答案
您收到的调用本质上是异步的,因此当您尝试分配结果时,结果可能尚未填充。
所以这里
var adv = $adviceList.AdviceList();
$scope.treatments = adv.treatments; //The treatments would only get filled after the server call is over.
您需要重写代码,以便在成功回调时将其分配给范围属性。
关于javascript - 取消设置对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17699595/