Search code examples
javascriptangularjsangular-ui-router

AngularJs mutliple layouts for different routes


I am trying to setup a complex AngularJS based application with multiple templates and layouts. But i don't really understand the routing mechanism of angularjs, so i am looking for further explanation about it and maybe some examples if possible.

I have many layouts that I would like to use with different templates based on routes.


Error Pages:

It's a simple error page with different messages to the user.

Layout:

layouts/error.html

Templates:

templates/error/404.html
templates/error/505.html
templates/error/403.html

These pages

Internal Pages:

To visit these pages it is required for the users to sign in.

Layout:

layouts/internal.html

This layout has a sidebar on the left side that has a menu and a chat box that diplays messages from other logged in users, and i would like to avoid it to be reloaded when the user is navigating.

Template Routes:

/dashboard -> templates/internal/dashboard.html
/profile -> templates/internal/profile.html
/settings -> templates/internal/settings.html
/library -> templates/internal/library.html
etc..

Public Pages:

Public pages that are available for anyone.

Layout:

layouts/public.html

Templates:

registration -> templates/public/registration.html
sign in -> templates/public/signin.html
forgot password -> templates/public/forgotpassword.html
about us -> templates/public/aboutus.html
etc..

How should i set up the routing for this in angularjs?


Solution

  • Create an empty main-Layout (eg index.html) which contains nothing but a ng-view container in the body. The view can be changed depending on the route.

    Example:

    <!doctype html>
    <html lang="en" ng-app="phonecatApp">
    <head>
    ...
      <script src="bower_components/angular/angular.js"></script>
      <script src="bower_components/angular-route/angular-route.js"></script>
      <script src="js/app.js"></script>
      <script src="js/controllers.js"></script>
    </head>
    <body>
      <div ng-view></div>
    </body>
    </html>
    

    Then you can include different partials in the ng-view depending on the route. For more details and example code, see this tutorial: https://docs.angularjs.org/tutorial/step_07

    If you want to build more complex layouts with nested views/templates, take a look at ui-router: https://github.com/angular-ui/ui-router