javascriptangularjsurl-routingnested-views

Inserting different views in Angular using the ng-view Directive


Can anyone help me with this view issue that I have. This is a hypothetical example so there is no code to see.

So say I have a site simple site with three routes

/signin 
/users 
/users/:id

I hit the sign-in route (/signin) and the sign-in view is inserted into <ng-view> in the index.html. The sign-in view is a simple form with username and password.

After a successful sign-in I arrive at the user list view (/users), which contains say a header, footer, left-side-nav and the user list as the main content in the middle.

I then click on a user in the list and I’m taken to the user detail page (/users/:id). The problem I have now is i only want to update the main content. I dont want to keep inserting the header, footer and left-nav into the view. So to get around that I could do this in my index.html

<header/>
<left-nav/>
<div ng-view></div>
<footer/>

Now when I change routes only the main content changes but the issue I have now is if I return to the signin screen it now contains a header, footer and nav that I dont want.

This ideally what I want.

How do I make this work without some hooky fix?


Solution

  • What you want is basically a nested views and states. So that all routes under /parent like /parent/:id have the same layout. As of now angular ngRoute doesn't support nested ng-views. There are two ways of solving this

    1. Use the ng-include's and a separate service to handle the routing logic i.e. when to use ng-include to get the layout (header, footer, menu) for this route and of what type.
    2. Use ui-router which supports nested routing out of the box and will likely be incorporated into the angular-core sooner or later.

    Toggling visibility of the elements according to the current route is a fast way to a messed code and a lot of nested conditional statements if you are going to have more than two different layouts.

    Hope this example helps JsBin Example. Feel free to ask additional questions regarding the nested views.