AngularJS在加载控制器之前加载数据

时间:2013-08-27 18:55:05

标签: javascript angularjs

如果在页面加载之前我如何处理从服务加载数据?

我试过使用resolve但问题是我还没有创建我需要调用的服务所以我必须在resolve函数中执行所有的服务逻辑,我实际上并不是这样想做。

我目前有一种处理它的工作方式,但当然加载视图内容和服务实际返回填充所需数据之间存在延迟:

myApp.service('WorkshopGetStoreState',  ['Transaction', 'ExpServices', 'CacheService', function(Transaction, ExpressServices, CacheService) {
    return {
        submit:function(defer) {
            var requestTemplate = ExpServices.getRequestTemplate('WorkshopGetStoreState');
            var request = requestTemplate.template;
            var params = {};
            params.action = "getStoreAddress";
            params.locationInfo = [{'storeId': '004141' }];
            for (var attrname in params) {
                request.service.serviceRequest[attrname] = params[attrname];
            }
            Transaction.submit(requestTemplate.url, request, defer);
            return defer.promise;
        }
    };
}]);

myApp.factory('WorkShopFlowService',['WorkShopGetStoreState',  function(WorkshopGetStoreState) {
    var address={};

    return {
        getStoreAddress : function() {
            return address;
        },
        setStoreAddress : function(addressParam) {
            address = addressParam;
        },
        init : function(defer){
        var promise = WorkshopGetStoreState.submit(defer);
        return promise;
    }
    };
}]);

myApp.controller('WorkshopLandingCtrl', [ '$scope', 'WorkShopFlowService', '$q', function($scope, WorkShopFlowService, $q) {
    var defer = $q.defer();
    var storedAddress = WorkShopFlowService.getStoreAddress();
    if (storedAddress) {
        $scope.address = storedAddress; 
    }
    else {
        WorkShopFlowService.getDefaultLocation(defer).then(function(result) {
        $scope.address = result.serviceResponse.storeInfo[0];
        WorkShopFlowService.setStoreAddress($scope.address);
        });
    }
}]);

编辑:现在似乎支持在较新版本的AngularJS中将对象引用为字符串名称,因此现在可以通过这种方式执行此操作。

0 个答案:

没有答案