0

When my page loads I want to make an http call to the server to see if the user's login session is still valid. The client will send a session key with the current timestamp, and server will compare that timestamp to see if it is longer than its specified timeout period. The server will then return either true or false.

If the http call returns true and the login is valid I want to generate this html:

<li><a href='#logout'>logout</a></li>

If the call returns false and the login has expired I want to show the following:

<li><a href='#login'>login</a></li>

I am not sure how to do this with AngularJS.

2 Answers 2

2

Angular has built-in directives for conditional rendering:

ng-show / ng-hide: conditionally set display: none style (with .ng-hide class)

ng-if / ng-switch: conditionally add/remove DOM elements.

Either approach would work here. For example:

<li ng-switch="isLoggedIn">
  <a ng-switch-when="true"  href='#logout'>logout</a>
  <a ng-switch-when="false" href='#login'>login</a>
</li>

isLoggedIn can be set whenever you complete the HTTP call.

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

Comments

1

Create a controller

angular.module('yourModuleName').controller('sessionCtrl', ['$scope', '$http', function($scope, $http){
    $http.get('url')
        .success(function(data){
            $scope.loggedIn = data ? '#logout' : '#login'; //true or false 
        })
}]);

And then in your markup

<div ng-controller="sessionCtrl"> 
    <li ng-show="loggedIn"><a href='{{loggedIn}}'>logout</a></li>
</div>

EDIT: You can use ng-if/ng-switch instead of ng-show to optimise performance because this will actually remove the dom object instead of hiding it. However, in your case it shouldn't matter too much. Furthermore, keep in mind if you're using a version below 1.2, you may not get access to ng-if. ng-switch is also somewhat verbose.

1 Comment

I'd vote for ng-switch, or ng-if and avoid even generating the templates not used.

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.