Search code examples
angularjscookiessession-cookiesangular-ng-if

How to use ng-if in front end if my condition is in saved in cookies?


As I've started learning angulerjs I'm facing small issues. while developing angulerjs application.

I've setup login process recently, now I'm stuck on front-end display. if the user is logged in I want to display specific content. for example:

 <!--show this if cookies is set to true -->
<li><a href="#/logout"><span class="icon mail"></span>Logout</a></li>
<!-- show this if cookies is undefined -->
<li><a href="#/login"><span class="icon mail"></span>Login</a></li>

All I know I will have to use ng-if for this. how can I check conditions for ng-if, if login value stored in cookies?

controller

app.controller('AngularLoginController', ['$scope', '$http','$cookies', 
function($scope, $http, $cookies) {  
    $scope.loginForm = function() {         
            $http.post("login.php", {
            'email' :$scope.inputData.email,
            'password':$scope.inputData.password
            }).success(function(data) {
                console.log(data);                  
                if ( data == 'correct') {                   
                var loggedIn = $cookies.get('loggedIn');
                // Setting a cookie
                $cookies.put('loggedIn', true);
                //window.location.href = 'welcome_dashboard.php';
            } 
            else {
                $scope.errorMsg = "Invalid Email and Password";
            }
        })
        }

    }]);

Solution

  • Create an function in your controller to get the cookie here am using simple javascript

    function getCookie(name) {
      var value = "; " + document.cookie;
      var parts = value.split("; " + name + "=");
      if (parts.length == 2) return parts.pop().split(";").shift();
    }  
    

    check if cookie exist

    $scope.hasCookie=function(){
        var ck=getCookie("your cookie name");
        if(ck && ck !="")
        return true;
    
      return false;
    }
    

    Html

      <!--show this if cookies is set to true -->
    <li ng-if="hasCookie()"><a href="#/logout"><span class="icon mail"></span>Logout</a></li>
    <!-- show this if cookies is undefined -->
    <li  ng-if="!hasCookie()"><a href="#/login"><span class="icon mail"></span>Login</a></li>