angular-ui / ui-router

The de-facto solution to flexible routing with nested views in AngularJS
http://ui-router.github.io/
MIT License
13.54k stars 3k forks source link

Angular UI router access parent state resolved data in child state #3604

Closed shashivardhan closed 6 years ago

shashivardhan commented 6 years ago

I would want to pass parent states already resolved data to child state onEnter function instead of again making an http call. I wanted to do this dynamically instead of passing the parent's resolve because I am generating multiple child states programatically as I will need to use the same child states for multiple parents and I have an angular service which does that.

I recently upgraded angular-uirouter from 0.2 to 1.0.8. Previously I used angular-ui-router extras and was able to achieve this using $state.$current.locals.globals., I injected $state to onEnter.

Instead of doing this hard-coded way

$stateProvider
  .state('parent',
    resolve:
      parentResolve: (Restangular) -> Restangular.all('route')
  )
  .state('child',
    parent: 'parent'
    url: '/child'
    resolve:
      childResolve: (Restangular) -> Restangular.one('bar')
    onEnter: ($modal) ->
      $modal.open(
        templateUrl: 'templates/modal.html',
        controller: 'ModalCtrl'
        resolve:
          parentResolve: -> parentResolve
          childResolve: -> childResolve
      )
  )
christopherthielen commented 6 years ago

Injecting parent resolve data into a child's onEnter has always been supported. You simply have to add them as args to your onEnter

$stateProvider
  .state('parent',
    resolve:
      parentResolve: (Restangular) -> Restangular.all('route')
  )
  .state('child',
    parent: 'parent'
    url: '/child'
    resolve:
      childResolve: (Restangular) -> Restangular.one('bar')
    onEnter: ($modal, childResolve, parentResolve) ->
      $modal.open(
        templateUrl: 'templates/modal.html',
        controller: 'ModalCtrl'
        resolve:
          parentResolve: -> parentResolve
          childResolve: -> childResolve
      )
  )

Alternatively you can inject the transition object and fetch them from there (see the docs for the API)

    onEnter: ($modal, $transition$) ->
      parentResolve = $transition$.injector().get('parentResove')
      $modal.open(
        templateUrl: 'templates/modal.html',
        controller: 'ModalCtrl'
        resolve:
          parentResolve: -> parentResolve
          childResolve: -> childResolve
      )