Set Default View for multiple states AngularJS ui.router Set Default View for multiple states AngularJS ui.router angularjs angularjs

Set Default View for multiple states AngularJS ui.router


Exactly that in is already there in UI-Router architecture:

Nested States & Nested Views

We will just declare a super base state (e.g. 'root'). It could even be abstract to avoid its initialization - but does not have to. And this state will define all the default views. Any child state or grand child state can replace any of these defaults:

The root state

 .state('root', {    // url: '/default', - no url needed at all, but could be    abstract: true    views:{        '' : { templateUrl: 'layout.html'},        'view_1@root': {            templateUrl: 'view1',            controller: function($scope){}        },        'view_2@root': {            templateUrl: 'view2',            controller: function($scope){}        },        'view_3@root': {            templateUrl: 'view3',            controller: function($scope){}        }    });

What we can see above, is that the root state injects into index.thml <div ui-view=""></div> its own template - the layout template:

'' : { templateUrl: 'layout.html'},

So all the named views inside of layout.html could be right now filled with default views, we just have to use the absolute naming (see below more)

'view_1@root': { // this will inject into the layout.html of current root state

Some more interesting points. We do not use url... so all child states can define its own. We use abstract... but it is not a must.

Child states - this is the way how to profit from parent

.state('changed_state', {    parent: 'root'           // this way we profit from parent    url: '/changed_state',    views:{        view_2: {            templateUrl: 'changed_view2',            controller: function($scope){}        },        // HERE all other views are unchanged 

Also check the:

Multiple Named Views

and

View Names - Relative vs. Absolute Names

to understand more the naming 'view_1@root' (small cite)

Behind the scenes, every view gets assigned an absolute name that follows a scheme of viewname@statename, where viewname is the name used in the view directive and state name is the state's absolute name, e.g. contact.item. You can also choose to write your view names in the absolute syntax.