首页 > 代码库 > ajax返回值给上层函数

ajax返回值给上层函数

var UserModule = angular.module("UserModule", []);

//用户收货地址服务
UserModule.factory("UserAddress", function ($http, $rootScope) {
    var AddressList = undefined;
    return {
        GetAddressList: function () {
            if (!AddressList) {
                $http.post("/api/addressController/dataGridAddress", { user_id: $rootScope.user.id }).success(function (data) {
                    if (data.success) {
                        AddressList = data.obj.rows;                       
                    }
                })
            }
            return AddressList;
        }
    }
})

UserModule.controller(‘AddressListCtrl‘, function ($scope, $http, UserAddress) {
     $scope.AddressList=UserAddress.GetAddressList();
});

上面代码有问题,$http.post是异步执行的,return AddressList;在AddressList = data.obj.rows;之前执行$scope.AddressList拿到的是undefined;

正确代码:

UserModule.factory("UserAddress", function ($http, $rootScope) {
    var AddressList = undefined;
    return {
        GetAddressList: function (callback) {
            if (!AddressList) {
                $http.post("/api/addressController/dataGridAddress", { user_id: $rootScope.user.id }).success(function (data) {
                    if (data.success) {
                        AddressList = data.obj.rows;
                        callback(AddressList);
                    }
                })
            } else {
                callback(AddressList);
            }

        }
    }
})

UserModule.controller(‘AddressListCtrl‘, function ($scope, $http, UserAddress) {
    UserAddress.GetAddressList(function (data) {
        $scope.AddressList = data;
    })
});

 

ajax返回值给上层函数