Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - $stateParams Is Empty In Controller

I am having a lot of trouble understanding how stateParams are supposed to work. Everywhere I look suggests that this should pass an item_id of 456 when I travel to the URL /#/manage/456, but instead $stateParams is an empty object. Furthermore, in the $state object that is passed to MainCtrl, I can access all of the parameters by using $state.params, however this seems to be undesirable and hackish.

angular
    .module('router',['ui.router'])
    .config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider)
    {

        $stateProvider
            .state('manage', 
            {
                url: '/manage',
                templateUrl: '/templates/main.html',
                controller: 'MainCtrl'
            })
            .state('manage.item_id',
            {
                url: '/:item_id',
                templateUrl: '/templates/main.html',
                controller: 'MainCtrl'
            })

    }])
    .controller('MainCtrl', ['$scope', '$stateParams', '$state', function($scope, $stateParams, $state)
    {
        // empty object
        console.log('$stateParams: ', $stateParams);

        // shows the variables i want
        console.log('$state.params: ', $state.params); 
    }])
like image 357
BlinkyTop Avatar asked May 15 '14 00:05

BlinkyTop


1 Answers

What you're trying to do should work fine, see this JSFiddle: http://jsfiddle.net/ahchurch/gf7Fa/14/

<script type="text/ng-template" id="item.tpl.html">
    embeded item template
</script>

<script type="text/ng-template" id="main.tpl.html">
    <ul>
        <li><a href="#/manage/45">change route</a></li>
    </ul>
    <div ui-view></div>
</script>

<div ui-view></div>


angular.module('myApp',['ui.router'])
    .config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider)
    {
        $urlRouterProvider.otherwise("/manage");
        $stateProvider
            .state('manage', 
            {
                url: '/manage',
                templateUrl: 'main.tpl.html',
                controller: 'MainCtrl'
            })
            .state('manage.item_id',
            {
                url: '/:item_id',
                templateUrl:'item.tpl.html',
                controller: 'MainCtrl'
            })
    }])
.controller('mainController', function(){})
    .controller('MainCtrl', ['$scope', '$stateParams', '$state', function($scope, $stateParams, $state)
    {
        // empty object
        console.log("main controller"); 

        console.log($stateParams);
    }]);

One thing I noticed is that your template is the same file for both states, so you may just be seeing the initialization of the "manage" state, and never seeing the "manage.item_id" state.

like image 86
Andrew Church Avatar answered Oct 01 '22 08:10

Andrew Church