admin管理员组

文章数量:1418380

$stateProvider.state('home', {
  url: '/', 
  resolve: {
    person: function() { 
      return 'good' 
    } 
  }

like above state config, how can I get the 'person' value in $stateChangeSuccess callback function ?

$rootScope.$on('$stateChangeSuccess', 
  function(event, toState, toParams, fromState, fromParams) {
    // I want get the 'person' value in this function, what should I do?
});
$stateProvider.state('home', {
  url: '/', 
  resolve: {
    person: function() { 
      return 'good' 
    } 
  }

like above state config, how can I get the 'person' value in $stateChangeSuccess callback function ?

$rootScope.$on('$stateChangeSuccess', 
  function(event, toState, toParams, fromState, fromParams) {
    // I want get the 'person' value in this function, what should I do?
});
Share Improve this question edited Jul 8, 2014 at 15:54 Duoduo asked Jul 8, 2014 at 14:14 DuoduoDuoduo 5091 gold badge5 silver badges11 bronze badges 1
  • What does it mean when you say "No 'person' in toState"? What are you trying to acplish? – Jobsamuel Commented Jul 8, 2014 at 14:23
Add a ment  | 

2 Answers 2

Reset to default 13

We had the same problem. We solved it by relying on some internal implementation details of ui-router; this does mean that it might break in a future version of angular, but here is the function we used:

function annotatedStateObject(state, $current) {
    state = _.extend({}, state);
    var resolveData = $current.locals.resolve.$$values;
    state.params = resolveData.$stateParams;
    state.resolve = _.omit(resolveData, '$stateParams');
    state.includes = $current.includes;
    return state;
}

That will get the params, includes, and all the (resolved) resolve objects. We use that in the callback like so:

$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
    toState = annotatedStateObject(toState, $state.$current);

    var person = toState.resolve.person;
}

I hope that helps!

Taxilian's answer is perfect except I'm not using Lodash so I implemented _.omit. Here is my result.

function annotatedStateObject(state, $current) {
    state = angular.extend({}, state);
    var resolveData = $current.locals.resolve.$$values;
    state.params = resolveData.$stateParams;
    state.resolve = omit(resolveData, '$stateParams');
    state.includes = $current.includes;
    return state;
}

function omit(obj, arr) {
    arr = Array.isArray(arr) ? arr : [arr];
    arr.forEach(function(key){
        delete(obj[key]);
    });
    return obj;
}

本文标签: