1

I'm trying to delay loading other controllers until authentication has taken place in my MainCtrl.

index.html:

<body ng-app="MyApp" ng-controller="MainCtrl">
...
    <div ng-view>
        ...
    </div>
...
</body>

MainCtrl:

var checkAuth = function () {
    var deferred = $q.defer();

    userAuth.isAuthenticated(

    function () {
        $rootScope.user = userAuth.user.data;
        deferred.resolve();
    }, function () {
        $rootScope.user = false;
        deferred.resolve();
    });

    return deferred.promise;
};

$scope.$watch('$location.path()', function () {

    $rootScope.$on('$locationChangeSuccess', function (event) {
        checkAuth();

    });
});

What I want is for the checkAuth function to run and then if the user is authorised, to load a partial and controller.

I have tried various solutions as suggested in similar questions (Delaying AngularJS route change until model loaded to prevent flicker, Angular.js delaying controller initialization, AngularJS - prevent not authenticated user from accessing given routes) but the problem is that none of them work when the page is refreshed or if the user is arriving from an external page. I've tried to use $locationChangeSuccess to run the authentication on page load but the partial controller doesn't wait for the authentication to be run before loading.

Can anyone suggest a better solution or where I might be going wrong with my approach?

Community
  • 1
  • 1
Niall Ryan
  • 11
  • 3
  • What is your current code relating to loading partial? Partials are not loaded until you use manually load it in your code. – zs2020 Aug 20 '13 at 14:00
  • @NiallRyan Use `$routeProvider`'s `resolve`. – AlwaysALearner Aug 20 '13 at 14:12
  • @Codezilla Have tried that and it only works within the app, so if a user types in a URL to navigate directly to a route, or if the user refreshes the page, the function in the resolve property will not run. – Niall Ryan Aug 20 '13 at 14:18
  • @NiallRyan In the above case do you get any error or the controller does not wait for the auth to be run before loading? – AlwaysALearner Aug 20 '13 at 14:20
  • @Codezilla The controller doesn't wait for the auth to be run. – Niall Ryan Aug 20 '13 at 14:27
  • @sza I'm using ng-view to load templates/partials, defined using $routeProvider in app.js, the standard approach. – Niall Ryan Aug 20 '13 at 14:27
  • @NiallRyan Using `resolve` should work. Generally it resolves all the dependencies before instantiating the controller. – AlwaysALearner Aug 20 '13 at 14:29
  • @Codezilla I thought so too but it doesn't work unless you're already in the app and using links to navigate, if you try to use the address bar to navigate, or refresh the page, the function in the resolve property does not run. – Niall Ryan Aug 20 '13 at 14:32

0 Answers0