小编fri*_*itz的帖子

Angular .controller()在.run()之前运行

我在.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) { ...
Run Code Online (Sandbox Code Playgroud)

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

感谢@misterhiller(twitter)

dependencies controller angularjs

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

angularjs ×1

controller ×1

dependencies ×1