0

I have AuthService and want to use this service in some controllers.

I want to show or hide "log out" button in my front-end, depends on $scope.isLoggedIn.

My front-end code:

<md-button ng-if="isLoggedIn" class="md-button" ng-click="signOut()" aria-label="Logout">
    Logout
</md-button>

and my signOut() function:

$scope.signOut = function() {
    AuthenticationService.signOut().then(function() {
        $location.path('/');
    });
};

Authentication service contains functions: signIn(), signOut() and field .isLoggedIn = true|false.

And I want to update my variable in controller, $scope.isLoggedIn depends on AuthenticationService.isLoggedIn. But if I try this:

$scope.isLoggedIn = AuthenticationService.isLoggedIn

it works OK, but only when I load site. So if user is logged in, variable $scope.isLoggedIn is true and if user isn't logged in variable $scope.isLoggedIn is false.

But if AuthenticationService.isLoggedIn change while application runs it doesn't change $scope.isLoggedIn.

Is it possible to keep this reference between service and controller? Or should I do this in another way?

3 Answers 3

3

You'll have to do:

$scope.authService = AuthenticationService;

And in your view, access it by:

authService.isLoggedIn

The reason your current way isn't working is because you're setting a boolean initially, a value type, not a reference type like an object. So when isLoggedIn is updated, your scope variable doesn't know. When you set it to an object, in your case AuthenticationService, the reference to that object is maintained, and any updates are reflected in the view.

Sign up to request clarification or add additional context in comments.

Comments

1

use also $watch in controller

$scope.$watch(function(){return AuthenticationService.isLoggedIn}, function(newval, oldval){
   $scope.isLoggedIn = newval;
});

1 Comment

This will work, but it is a bad practice. You don't need to use $watch to accomplish this.
1

Simply make this into a function:

$scope.isLoggedIn

$scope.isLoggedIn = function(){ return AuthenticationService.isLoggedIn;}

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.