Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...