Search code examples
javascriptangularjsangularjs-service

AngularJS: Refresh angular scope outside of ng-view


OK, so I have a basic login page that when the user logs in I want to then display more details on the navbar at the top of the screen. When they click logout, this then goes away. This is working (in a way) however to get the navbar to change I need to refresh the page, which obviously does not happen when i just use routing to change what is in my ng-view.

When the user clicks 'log in' their username is stored in a service which is called using the login controller that is within the ng-view.

authService.SetUsername(user.Username);

However I want this to have an effect in my navbar controller which is outside the ng-view.

Here you can see in my trimmed down navbar controller how this is being used.

app.controller('navbarController', function ($scope, authService, $cookies, $location) {

    $scope.displayUsername = authService.GetUsername();

});

But displayusername is only changed when the page is refreshed and the controller is 'reloaded'. How do I get this to change instantly when the service storing the username is updated?


Solution

  • You can broadcast a login event:

    .factory("authService", [
        "$rootScope",
        function ($rootScope) {
            return {
                login: function () {
                    // do the login
                    $rootScope.$broadcast("login-done");
                }
            }
        }
    ]);
    

    and your controller:

    app.controller('navbarController', function ($scope, $rootScope, authService, $cookies, $location) {
    
        $scope.displayUsername = authService.GetUsername();
    
        $rootScope.$on("login-done", function() {
            $scope.displayUsername = authService.GetUsername();
        });
    });