Question

I'm using ui-router for AngularJS.

I've defined some states like this.

    $stateProvider.state(
        {
            name:       'home',
            url:        '^/?page&find',
            controller: controller,
            data:       new cgTag.States.StateData('home', type),
            resolve:    resolve
        }
    );

I'm using a resolve to get some JSON from the server before the controller for the state is executed, but I need the state.data object for this state in the resolve function.

My resolver is like this

function _resolve($http, $state, $stateParams)
{
    var data = $state.current.data;
    // ^^^^ this is the wrong state
    return $http.post('/json/templates/layout', data);
}

var resolve = {
    'layoutResponse': ['$http', '$state', '$stateParams', _resolve]
};

$stateProvider.state(
    {
        name:       'home',
        url:        '^/?page&find',
        controller: controller,
        data:       new cgTag.States.StateData('home', type),
        // ^^^ I need this object in my resolve function.
        resolve:    resolve
    }
);

My problem is that $state.current is not the state being transitioned too. It's the from state.

How can I get the state.data object inside my resolve function for the state being resolved?

Was it helpful?

Solution

You can get the data for the current state by calling this.data from within the resolve function.

.config(function ($stateProvider) {
  $stateProvider
  .state('someState', {
    url: '/',
    resolve: {
      resolveThis: function () {
        alert(JSON.stringify(this.data)); // alerts you with delicious bacon
      }
    },
    data: {
      bacon: 'delicious'
    }
  });
});

http://plnkr.co/edit/OMc5ilofyA4sv66JMQe9?p=info

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