Question

Plunkr demonstrating problem:

http://plnkr.co/edit/Czc5kGpCwsruUQe2EanZ?p=preview

With the states:

.state('state1', {
  url: '/state1',
  template: '<div>state1 <pre>{{current | json }}</pre><div ui-view=""></div> </div>',
  controller: 'State1Ctrl',
})
.state('state1.list', {
  url: '/list',
  template: '<div>list <pre>{{current | json }}</pre></div>',
  controller: 'State1ListCtrl',
})

And the controllers:

.controller('State1Ctrl', function($scope, $state, $rootScope, $controller) {
  $scope.current = $state
})

.controller('State1ListCtrl', function($scope, $state) {
  $scope.current = $state
})

Produces the result:

state1
{
  "url": "/list",
  "template": "<div>list <pre>{{current | json }}</pre></div>",
  "controller": "State1ListCtrl",
  "name": "state1.list"
}

list
{
  "url": "/list",
  "template": "<div>list <pre>{{current | json }}</pre></div>",
  "controller": "State1ListCtrl",
  "name": "state1.list"
}

When going directly to the state1.list state.

I need access to the state that the controller is associated with, e.g. I want the result to be:

state1 (notice how this is different - it has the state1 configuration now)
{
  "url": "/state1",
  "template": "<div>list <pre>{{current | json }}</pre></div>",
  "controller": "State1Ctrl",
  "name": "state1"
}

list
{
  "url": "/list",
  "template": "<div>list <pre>{{current | json }}</pre></div>",
  "controller": "State1ListCtrl",
  "name": "state1.list"
}

I understand that state.$current is the current state, but how do you determine the state that the controller is associated with?

Was it helpful?

Solution

Controllers are meant to be independent of state in ui-router, so that the same controller could be used for any state.

But you can get any state from anywhere by using e.g. $state.get('state1.list')

I think you may just have to have someone somewhere know which controller is associated with which state. Whether each controller knows which state its associated with and calls $state.get('stateName') to get it, or you could build a service which will return the state for a controller name, or you could even use $state.get() to get all states and then enumerate through the list until one has a controller name that matches the controller that you are in.

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top