1

I'm using Angular's UI-Router as shown below to do URL-routing in my web-app as shown below:

$stateProvider.state('myState1', {
    url: '/state1',
    templateUrl: 'state1.html',
    controller: 'MyState1Ctrl'
  });

$stateProvider.state('myState2', {
    url: '/state2',
    templateUrl: 'state2.html',
    controller: 'MyState2Ctrl'
  });

Within each of the two template files state1.html, state2.html, I have my navigation bar directive: <myapp-navigation-bar></myapp-navigation-bar>. Here is the navigation bar's controller:

raptorApp.controller('NavigationCtrl', function($scope){
    var self = this;
    $scope.$watch(function() {return "something";}, function (objVal) {
        console.log('Hello from NavigationCtrl!');
    },true);
});

But I want the navigation bar to behave differently based on weather it is in myState1 or myState2. How can I detect from within NavigationCtrl which state it is in?

Saqib Ali
  • 11,931
  • 41
  • 133
  • 272

1 Answers1

2

we can always place anything into $scope and watch it. Even the $state service and its current.name. Something like (just a draft)

raptorApp.controller('NavigationCtrl', function($scope, $state){
    var self = this;
    $scope.state = $state;
    $scope.$watch("state.current.name", function (objVal) {
        console.log('current state name changed');
    },true);
});

NOTE: never forget to remove such watch on destroy

But with UI-Router.. there are better ways. Much better ways:

  • named views
  • multiple views

So we can have a parent state, with a view called 'myapp-navigation-bar' and that could be filled by each state... with a different implementation. See this for detailed how to and example

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

How do I load UI-router ui-view templates that are nested 3 states deep?

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • Radim, I just posted a question on your other answer here: http://stackoverflow.com/questions/28800644/nested-states-or-views-for-layout-with-leftbar-in-ui-router Could you please answer it? – Saqib Ali Nov 18 '16 at 08:44
  • @SaqibAli Check the example in that answer. IN that plunker.. click on the right upper corner icon... "launch the preview in a separate window" .. you will see any url once state is changed – Radim Köhler Nov 18 '16 at 09:12