Categories
angularjs express javascript node.js

AngularJS – show/hide nav items if user is logged in

I have a single-page AngularJS app, working with Express, node.js, and MongoDB via Mongoose. Using Passport for user management/authentication.

I’d like the navbar items to change based on whether a user is logged in or not. I’m having trouble figuring out how to implement it.

I find out if a user is logged in through an http request:

server.js

app.get('/checklogin',function(req,res){
if (req.user)
res.send(true);
else
res.send(false);

On the front end, I have a NavController calling this using Angular’s $http service:

NavController.js

angular.module('NavCtrl',[]).controller('NavController',function($scope,$http) {
$scope.loggedIn = false;
$scope.isLoggedIn = function() {
$http.get('/checklogin')
.success(function(data) {
console.log(data);
if (data === true)
$scope.loggedIn = true;
else
$scope.loggedIn = false;
})
.error(function(data) {
console.log('error: ' + data);
});
};
};

In my nav, I am using ng-show and ng-hide to determine which selections should be visible. I am also triggering the isLoggedIn() function when the user clicks on the nav items, checking whether the user is logged in during each click.

index.html

<nav class="navbar navbar-inverse" role="navigation">
<div class="navbar-header">
<a class="navbar-brand" href="https://www.faqcode4u.com/">Home</a>
</div>
<ul class="nav navbar-nav">
<li ng-hide="loggedIn" ng-click="isLoggedIn()">
<a href="https://www.faqcode4u.com/login">Login</a>
</li>
<li ng-hide="loggedIn" ng-click="isLoggedIn()">
<a href="https://www.faqcode4u.com/signup">Sign up</a>
</li>
<li ng-show="loggedIn" ng-click="logOut(); isLoggedIn()">
<a href="#">Log out</a>
</li>
</ul>
</nav>

Problem

There are other places in my app where the user can log in/out, outside of the scope of the NavController. For instance, there’s a login button on the login page, which corresponds to the LoginController. I imagine there’s a better way to implement this across my entire app.

How can I ‘watch’ whether req.user is true on the back end and have my nav items respond accordingly?