Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Handle repeated fragments like Header and Footer

I have been trying to implement the header / footer in an Angular JS App. I was thinking of adding these as ng-include in the main index.html. However this would have worked if the header and footer are static pages. My case is slightly different... In Login page no header / footer is shown. Other pages depending on whether you are logged in or not, you have to show "Welcome user [ logout] " or "Welcome guest [ login ]".

I save the login information in the rootScope as well as set a boolean $rootScope.isLoggedIn on login. The biggest problem seems to be that the whole ng-include is not refreshed on a logoff. Hence divs with ng-show hide directives will not hide/show on change. Somebody suggested using ng-switch - it also behaves the same way.

If I move the header code inside individual views then everything is fine.

A similar question is here: Refresh header page in angularjs

like image 404
Hari Gangadharan Avatar asked Oct 10 '13 03:10

Hari Gangadharan


1 Answers

Use a controller in the header/footer, as ivarni suggested. An example from an (experimental) app of my own:

In the index.html, the header will display a dynamically generated menu, login/logout etc:

<div id="navbar" class="navbar navbar-inverse navbar-fixed-top"
    x-ng-controller="NavbarCtrl" x-ng-include="'app/main/navbar.html'"></div>

The NavbarCtrl builds the appropriate scope for the app/main/navbar.html template. The template would be as follows (taking into account your needs - and irrelevant details removed):

<div class="navbar-inner" x-ng-if="showHeader">
    <div class="container">
        <div>
            <ul class="nav">
                <li x-ng-repeat="menuEntry in menuEntries">
                    <a x-ng-href="#{{menuEntry.path}}">{{menuEntry.display}}</a>
                </li>
            </ul>
        </div>
    </div>
    <div x-ng-if="userData.loggedIn">
        Wellcome {{userData.userName}}!
        <a x-ng-click="logout()">Logout</a>
    </div>
    <div x-ng-if="!userData.loggedIn">
        <a x-ng-click="login()">Login</a>
    </div>
</div>

So the entire markup is hidden depending on the showHeader scope variable. It creates the menu dynamically (menuEntries). And depending on userData.loggedIn, the appropriate Login/Logout message.

like image 115
Nikos Paraskevopoulos Avatar answered Nov 15 '22 07:11

Nikos Paraskevopoulos