Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle header and footer with AngularJs

I'm very sorry If I don't explain myself very well, so here goes. Basically I'm having trouble trying to work this issue out. I am using Yeoman to generate my angular project. I have a header and footer, footer will be static and header will need its own controller. The problem I am having is, I don't particularly want the header to be outside other controllers. Maybe I'm wrong and it's not actually a problem and best practice would obviously be to have the header outside ng-view? This is what I have so far:

   <head>
     <!-- head stuff here -->
   </head>
   <body ng-app="dscover.me">

        <div ng-include src="'partials/header.html'"></div>  

        <div ng-view="">
        </div>

        <div ng-include src="'partials/footer.html'"></div>
   </body>

Is this a correct way of including a header and footer outside the MainCtrl? It makes sense to me only because, if I was to create a new controller / page, I'd still have access to the controllers outside it? The problem again is I want to refrain myself from using rootScope and unfortunately this seems to be the only way when it comes to having the header outside the MainCtrl?

I'm sorry for the terrible explanation, but I hope you guys understand. If there is a better way of doing this, please let me know. Any help will be appreciated!

like image 614
Sananes Avatar asked Nov 22 '13 10:11

Sananes


1 Answers

First of all, I would try to rely on the given functionality of AngularJS as possible. There are three ways to implement the header and footer in the app:

  1. ng-include

The reason why you'd like to use it is simplicity and less to code. From docs:

Fetches, compiles and includes an external HTML fragment

So, it simply includes an external chunk of html.

  1. ng-view

This is a default router in Angular (before 2.0) and there is a better option called ui-router.

The UI-Router is a routing framework for AngularJS built by the AngularUI team. It provides a different approach than ngRoute in that it changes your application views based on state of the application and not just the route URL.

It supports features like nested views etc. The main reason to use it would be to separate controllers and scopes of those views. In terms of headers and footers, if you want to have a completely separate logic inside, then go for it.

  1. custom directive

This option should be used in case if you have a logic overlapping in the main content scope and header / footer. Also you get additional perks with it like reusability etc.

So, your choice to pick one, but don't be lazy to search and read (here, here, here or here) before you write.

like image 88
boldnik Avatar answered Oct 12 '22 07:10

boldnik