Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular .controller() runs before .run()

I have an ajax call inside the .run() that loads a variable into the $rootScope That variable is needed in the controller associated with a view.

Sometimes on refresh (F5) by the time the .controller is loading there is nothing inside $rootScope.user.fedUnit resulting in:

TypeError: Cannot read property 'fedUnit' of undefined

Any way to delay loading the controller until after the .run() is finished? Can't seem to find it.

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) { ...

Solution

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

thanks to @misterhiller (twitter)

like image 478
fritz Avatar asked Jun 06 '13 14:06

fritz


1 Answers

The solution at functional code block:

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

I don't use $rootScope in the controller.

like image 85
N0rdl1cht Avatar answered Nov 27 '22 17:11

N0rdl1cht