Reputation: 784
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?
Upvotes: 0
Views: 76
Reputation: 21
Simply make this into a function:
$scope.isLoggedIn
$scope.isLoggedIn = function(){ return AuthenticationService.isLoggedIn;}
Upvotes: 1
Reputation: 1479
use also $watch in controller
$scope.$watch(function(){return AuthenticationService.isLoggedIn}, function(newval, oldval){
$scope.isLoggedIn = newval;
});
Upvotes: 1
Reputation: 1349
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.
Upvotes: 3