How do I setup nested views in AngularJS?

2019-01-21 22:34发布

问题:

I have an application with various screens. Each screen is assigned a URL, such as #, mails, contacts, and so on.

In my main HTML file I have an ng-view element which updates according to the route the user selects. So far, so good.

Now some of these screens have a sub-navigation. E.g., #mails does have an inbox and a sent folder. They present themselfes with two columns: The sub-navigation on the left, the mails of the appropriate folder on the right.

When you navigate to #mails, it shall redirect you to #mails/inbox, so that basically inbox is the default sub-view for mails.

How could I set this up?

The only approach I can currently think of (I am quite new to AngularJS, hence forgive me if this question is a little bit naive) is to have two views, one for #mails/inbox, and the other for #mails/sent.

When you select a route, these views are loaded. When you select #mails it simply redirects you to #mails/inbox.

But this means that both views must use an ng-include for the sub-navigation. Somehow this feels wrong to me.

What I'd like more is to have nested views: The top one switches between screens such as mails, contacts, and so on, and the bottom one changes between sub-views such as inbox, sent, and so on.

How would I solve this?

回答1:

AngularJS ui-router solved my issues :-)



回答2:

Another library to check out: http://angular-route-segment.com

You can use it instead of built-in ng-view and $route.

Sample route config looks like this one:

$routeSegmentProvider.

when('/section1',          's1.home').
when('/section1/prefs',    's1.prefs').
when('/section1/:id',      's1.itemInfo.overview').
when('/section1/:id/edit', 's1.itemInfo.edit').
when('/section2',          's2').

segment('s1', {
    templateUrl: 'templates/section1.html',
    controller: MainCtrl}).

within().

    segment('home', {
        templateUrl: 'templates/section1/home.html'}).

    segment('itemInfo', {
        templateUrl: 'templates/section1/item.html',
        controller: Section1ItemCtrl,
        dependencies: ['id']}).

    within().

        segment('overview', {
            templateUrl: 'templates/section1/item/overview.html'}).

        segment('edit', {
             templateUrl: 'templates/section1/item/edit.html'}).

        up().

    segment('prefs', {
        templateUrl: 'templates/section1/prefs.html'}).

    up().

segment('s2', {
    templateUrl: 'templates/section2.html',
    controller: MainCtrl});