ngHide/ngShow using $rootScope in Single Page Application

Ajay Srikanth picture Ajay Srikanth · Jan 2, 2015 · Viewed 16.9k times · Source

Reaching out to you all for help yet again for AngularJS. I'm building a SPA where my Layout (master) Page is divided in to three section left navigation bar, center content, right item list bar. My right item list should be hidden when I load my home page, but should be visible in the remaining screens. I've created a $rootScope variable in the homeController and setting the value to 'true' based on the location path and using that variable in the template to set the value to ngHide. When I navigate to a different page as I'm using SPA, my right and left bars won't be loaded again, only my center content do which is a new view. While loading the new view in the controller that is sending the data to the new view's template I'm resetting the $rootScope variable that I've created in homeController to 'false', but my right bar is still not visible. I could see that ng-hidden class is still on though the interpollation has updated the value to 'true'. Any suggestions would be highly appreciated.

markup from layout page:

<aside class="right_bar" ng-hide="{{$root.show}}">
        <div class="my-list"><span class="f3">My Cart</span><div class=""><span class="list-count">0</span></div></div><div class="list-item"><ul></ul></div>
    </aside>  

homeController code:

    function getHomeConfigsCtrl($http, $location, $rootScope) {

     $rootScope.show = false;

    var loc = $location.path();

    if (loc === '/Home/Index' || loc ==='')
    {
        $rootScope.show = true;
    }
   }

Categories Controller code: This is where I'm resetting my $rootScope variable's value

function getAllCategoryDetails($routeParams,$rootScope) {
    $rootScope.show = false;
}

Answer

teleaziz picture teleaziz · Jan 2, 2015

Two things about angular you need to know to make your presented code works:

  • You don't need to interpolate values using {{}} in ng directives, instead use ng-hide="showCart".

  • Assuming all your controllers are within the same angular application, all scopes within the same application inherits from the same root, i.e whatever you define on the $rootScope will be available to all child scopes. To access the $rootScope.x from within any view in the application all you have to do is: {{x}} or in your case you're using it inside a directive you can do something like this:

    <aside class="right_bar" ng-hide="showCart">

    This will look for your current scope, if it has a showCart then it'll use it, otherwise it'll fetch the $rootScope.showCart