5

我在 .run() 中有一个 ajax 调用,它将一个变量加载到 $rootScope 中,与视图关联的控制器中需要该变量。

有时在 .controller 加载时刷新(F5),$rootScope.user.fedUnit 内没有任何内容,导致:

TypeError:无法读取未定义的属性“fedUnit”

有什么方法可以延迟加载控制器直到 .run() 完成?好像找不到

app.run(function($rootScope, $http, $location, SessionFactory, TokenHandler) {
    token = TokenHandler.getToken();
    if ( token != null ) {
        SessionFactory.get( { token : token },
            function success(response, responseHeaders) {
                $rootScope.user = response;
            }
        );
    }
});

app.controller('UnitController', function($scope, $rootScope, $location, UnitFactory) {
    $scope.updateUnits = function () {
        UnitFactory.query({fedUnit: $rootScope.user.fedUnit}, function success(response, responseHeaders) { ...

解决方案

$rootScope.foo = $q.defer();
$rootScope.foo.resolve(); when AJAX is done;
$rootScope.foo.promise.then(..) in the controller.

感谢@misterhiller(推特)

4

1 回答 1

7

功能代码块的解决方案:

app.run(function($rootScope, $http, $q, SessionFactory, TokenHandler) {

    $rootScope.ajaxCall = $q.defer();

    token = TokenHandler.getToken();
    if ( token != null ) {
        SessionFactory.get( { token : token },
            function success(response, responseHeaders) {
                $rootScope.user = response;

                $rootScope.ajaxCall.resolve();
            }
        );
    }
});

app.controller('UnitController', function($scope, UnitFactory) {

    $scope.ajaxCall.promise.then(function() {
        $scope.updateUnits = function () {
            UnitFactory.query({fedUnit: $scope.user.fedUnit});
        }
    });
});

我不在控制器中使用 $rootScope 。

于 2013-08-21T17:31:02.600 回答