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?

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

2 Comments

Radim, I just posted a question on your other answer here: stackoverflow.com/questions/28800644/… Could you please answer it?
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.