Skip to content Skip to sidebar Skip to footer

How Do I Put A LocalStorage Var Inside My Ng-show ? (Angular JS/Firebase)

SITUATION: When I load a page and didn't log in yet, everything works fine and I only see Login and Register in my nav as should be the case. But when I log in and I load any page

Solution 1:

You can use the angular ng-cloak directive in order to prevent the AngularJS html template from being briefly displayed by the browser in its raw (uncompiled) form while your application is loading.

ngCloak documentation

<html ng-app="app" ng-cloak>
      <ul class="nav navbar-nav">
            <li ng-show="!authenticated"><a href="/users/register">JOIN</a></li>
            <li ng-show="!authenticated"><a href="/users/login">Login</a></li>
            <li ng-show="authenticated"><a href="/users/profile">ME</a></li>
            <li ng-show="authenticated" onclick="signOut();"><a>Logout</a></li>
      </ul>
</html>

You should use the $window service to access variable created outside of the scope of your controller. On top of that, you should not create the (almost) same controller twice.

$window documentation

Using something like that (not tested):

firebase.auth().onAuthStateChanged(function(user) {
    console.log("CURRENT USER:" + firebase.auth().currentUser);
    app.controller('ctrl', function($rootScope, $window) {
        $scope.authenticated = $window.user != null;
        setAppCookie();
        // Compile the whole <body> with the angular module named "app"
        angular.bootstrap(document.body, ['app']);
    });
});

For local storage, you just need to use the regular one:

//Set item
localStorage.setItem("authenticated", JSON.stringify(firebaseUser));

//Get item
$scope.authenticated = JSON.parse(localStorage.getItem("authenticated"));

Solution 2:

You have declared the $rootScope, but I don't see where you injected..

Remember all dependencies have to be injected through the $inject dependency..

    Var app = controller('mycontroller', ['$rootScope', function($rootScope) {
}]);

Post a Comment for "How Do I Put A LocalStorage Var Inside My Ng-show ? (Angular JS/Firebase)"