1

I have two sections to my AngularJS app which need separate nav bars:

  • Patents

    • patent nav bar: list patents, add patents
  • Transactions

    • transaction nav bar: current transactions, transaction history

I have read How to attach navbar only on certain pages using ui-router?, where you can use views, but that is including the templateUrl in the state, where I have my templateUrl declared in the component like so:

$stateProvider
.state('patents', {
   url: '/patents',
   component: 'patents',
})

angular.module('myApp').component('patents', {
    bindings: { patents: '<' },
    templateUrl: '../templates/patents/list/list-patents.htm'
});

Question

What is the best approach to include different navigation in my templates/states when using components in ui-router? Apologies if the answer is straight forward.

Patrick McDermott
  • 1,220
  • 1
  • 15
  • 30

1 Answers1

1

Method 1

Through ng-include in your template:

<div ng-include="'link/to/template.html'"></div>

Method 2

More dynamically, you can create a custom <navigation> component, which sets the correct template through a $stateParam.

Router:

.state('patents', {
    url         : '/patents',
    component   : 'patents',
    params      : {
        navigation  : 'custom'
    }
})

And then, in your navigation component, you can use

template    : function($stateParams) {
    var navigation = $stateParam.navigation || 'default';
    return '<div ng-include="\''link/to/' + navigation + '.html'\'"></div>
},

So you only have to set the param in your router when there is a custom navigation for that page.

Make sure though to include <navigation> on every page.


Method 3

In case you don't want to include <navigation> on every page, you can also create a single navigation menu (like you probably have now), and add a controller, with the following method

app.controller('NavigationCtrl', function($rootScope, $state) {
    $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
        this.navigation = toParams.navigation;
    });
})

The you can capture the toParams on every route update, and use that to dynamically change the template:

Navigation template:

<div class="nav" ng-controller="NavigationCtrl as $ctrl">

    <div ng-if="$ctrl.navigation === 'default'">
        // Include default
    </div>

    <div ng-if="$ctrl.navigation === 'custom'">
        // Include custom
    </div>

</div>
Jeffrey Roosendaal
  • 6,872
  • 8
  • 37
  • 55