0

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?

2
  • Could you add the authService service code here to help you more? Commented May 26, 2015 at 15:05
  • You want refresh just scope? Can not you do refresh all page? Commented May 26, 2015 at 15:09

2 Answers 2

5

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();
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Since he is broadcasting from the $rootScope, it can be listened to on $scope in controller. Not a big deal, just 1 less dependency in the controller. Not sure if either way is more efficient otherwise
Works like a charm. Had no idea about the broadcast service before.
0
  1. Create variable $rootScope.displayName.
  2. Use {{ displayName }} in HTML markup for your navbar.
  3. Up on success on login page, update $rootScope.displayName.
  4. Praise AngularJS.

Usually, I recommend having object $rootScope.user where more information can be stored about user, not just displayName.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.