0

我有一个提供者:

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在我的控制器中可用。

4

2 回答 2

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
            });

        });
于 2013-07-17T12:28:46.560 回答
1

您收到的电话本质上是异步的,因此当您尝试分配结果时可能没有填充结果。

所以在这里

var adv = $adviceList.AdviceList();
$scope.treatments = adv.treatments;  //The treatments would only get filled after the server call is over.

您需要以将代码分配给成功回调的范围属性的方式重写代码。

于 2013-07-17T12:23:05.063 回答