Nested states or views for layout with leftbar in ui-router?

One way how to design scenario with 1) side bar, 2) action section and 3) main area could be like in this working example

Firstly the root state. Here is root state named ‘index’. It is abstract and could do some resolve for us. It does not effect child state naming and does not extend the url (because is undefined)

$stateProvider
    .state('index', {
        abstract: true,
        //url: "https://stackoverflow.com/",
        views: {
          '@' : {
            templateUrl: 'layout.html',
            controller: 'IndexCtrl'
          },
          'top@index' : { templateUrl: 'tpl.top.html',},
          'left@index' : { templateUrl: 'tpl.left.html',},
          'main@index' : { templateUrl: 'tpl.main.html',},
        },
      })

The first real state is list, and it inherits from parent but with an attribute parent: 'index', so the parent name is not effecting the state name.

Advantage is, that it could inherit lot of resolved stuff. Also, the root state could be loaded once, for all other parent states

    .state('list', {
        parent: 'index',
        url: '/list',
        templateUrl: 'list.html',
        controller: 'ListCtrl'
      })

This is the real power of UI-Router, because now we can see that child is injecting stuff into two places – 1) action section and 2) main area

    .state('list.detail', {
        url: '/:id',
        views: {
          'detail@index' : {
            templateUrl: 'detail.html',
            controller: 'DetailCtrl'
          },
          'actions@index' : {
            templateUrl: 'actions.html',
            controller: 'ActionCtrl'
          },
        },
      })

This way, we can use named views and multi views in real world scenario. Please, never forget how the scope definition goes:

Scope Inheritance by View Hierarchy Only

Keep in mind that scope properties only inherit down the state chain if the views of your states are nested. Inheritance of scope properties has nothing to do with the nesting of your states and everything to do with the nesting of your views (templates).

It is entirely possible that you have nested states whose templates populate ui-views at various non-nested locations within your site. In this scenario you cannot expect to access the scope variables of parent state views within the views of children states.

Check that all in action here

Leave a Comment