Gabriel Lopes
Gabriel Lopes

Reputation: 941

$state, $stateParams, getting undefined object

I am getting unexpected results from both methods.

I have my $state configed

    $stateProvider
                .state('status', {
                  url: "/status/:payment",
                  controller: 'QuestCtrl',
                  templateUrl: "index.html"
                });

And on the Controller I have:

    angular.module('quest').controller('QuestCtrl',function($scope,$stateParams,$state){

     console.log($stateParams.payment); // undefined

     console.log($state); // Object {params: Object, current: Object, $current: extend, transition: null}

}

I already used $stateParams in other projects and it worked but now I can't figure out what is going on here..

Upvotes: 5

Views: 14024

Answers (5)

MarceloBarbosa
MarceloBarbosa

Reputation: 915

Missing parameter in routes.js

My example:

  .state('menu.cadastroDisplay', {
    url: '/page9',
    views: {
      'side-menu21': {
        templateUrl: 'templates/cadastroDisplay.html',
        controller: 'cadastroDisplayCtrl'
      }
    },
    params: { 'display': {} }
  })

Without this params in routes the $stateParams.yourParam always returns undefined.

Upvotes: 2

Piyush Dhomne
Piyush Dhomne

Reputation: 41

Call 'ngInject' constructor($scope, $reactive, $stateParams, $state, $sce) { 'ngInject'

Upvotes: 0

Thomas Weglinski
Thomas Weglinski

Reputation: 1094

With the ng-annotate library, the controller can be also initiated like this:

angular.module('quest')
    .controller('QuestCtrl', function ($scope,$http,$stateParams,$state) {

});

In this case you are avoiding problems with the injected objects ordering. Look at: https://github.com/olov/ng-annotate

If you are building your application with Grunt, use: grunt-ng-annotate package.

Upvotes: 1

squiroid
squiroid

Reputation: 14037

As I already commented above You forgot to inject $http service

angular.module('quest').controller('QuestCtrl',
['$scope','$http','$stateParams','$state',function($scope,$http,$stateParams,$state){

 console.log($stateParams); // Empty Object
 console.log($stateParams.payment); // Empty Object

 console.log($state); // I get the entire state, I can see that my params are there.

console.log($state.params);
}

So your parameters mismatch and it turns out you will get $state in $stateparms and $state is empty. And $http hold $state :P

Hope it helps :)

Upvotes: 4

JB Nizet
JB Nizet

Reputation: 692211

        ['$scope','$stateParams','$state',
function($scope,  $http,          $stateParams, $state)

The names of the services don't match with the variables.

So $http is actually the $stateParams service, $stateParams is actually the $state service, and $state is undefined.

My advice: stop using this array notation, which clutters the code and is a frequent source of bugs. Instead, use ng-annotate as part of the build procedure, which will do it, correctly, for you.

Upvotes: 4

Related Questions