54

This is probably simple but I can't find anything in the docs and googling didn't help. I'm trying to define a state in $stateProvider where the URL I need to hit on the server to pull the needed data depends on a state URL parameter. In short, something like:

 .state('recipes.category', {
    url: '/:cat',
    templateUrl: '/partials/recipes.category.html',
    controller: 'RecipesCategoryCtrl',
    resolve: {
      category: function($http) {
        return $http.get('/recipes/' + cat)
          .then(function(data) { return data.data; });
      }
    }
  })

The above doesn't work. I tried injecting $routeParams to get the needed cat parameter, with no luck. What's the right way of doing this?

Devid Farinelli
  • 7,514
  • 9
  • 42
  • 73
kliron
  • 4,383
  • 4
  • 31
  • 47

2 Answers2

106

You were close with $routeParams. If you use ui-router use $stateParams instead. This code works for me:

.state('recipes.category', {
    url: '/:cat',
    templateUrl: '/partials/recipes.category.html',
    controller: 'RecipesCategoryCtrl',
    resolve: {
         category: ['$http','$stateParams', function($http, $stateParams) {
             return $http.get('/recipes/' + $stateParams.cat)
                    .then(function(data) { return data.data; });
         }]
     }
})
scniro
  • 16,844
  • 8
  • 62
  • 106
Reto
  • 3,107
  • 1
  • 21
  • 33
  • And how to get `category` in controller RecipesCategoryCtrl ? – dumitru Mar 28 '15 at 12:25
  • 1
    just inject it: `RecipesCategoryCtrl = function($scope, category) { $scope.cat = category }` – Reto Mar 28 '15 at 12:42
  • 1
    $stateParams will only return parameters that are given in the url (as {param} or :param). I do not want my target state to have a URL. Furthermore, the parameter is an object. To pass it this way I would have to convert it to JSON first then parse it back. Too slow and messy. – Lawrence I. Siden Oct 09 '15 at 18:14
10

For those who are using ui-router 1.0 $stateParams is deprecated, you should use $transition$ object instead:

.state('recipes.category', {
    url: '/:cat',
    templateUrl: '/partials/recipes.category.html',
    controller: 'RecipesCategoryCtrl',
    resolve: {
         category: ['$http','$transition$', function($http, $transition$) {
             return $http.get('/recipes/' + $transition$.params().cat)
                    .then(function(data) { return data.data; });
         }]
     }
})
31piy
  • 23,323
  • 6
  • 47
  • 67
G07cha
  • 4,009
  • 2
  • 22
  • 39