Search code examples
angularjsangular-ui-routerui-sref

Inject a resolve provider from child state to controller


So i'm trying to pull some id from the url parameters.

Here are my states :

$stateProvider
    .state('parent', {
        url: '/parent',
            templateUrl: 'path/to/parent.html',
            controller: 'lolController'
        })
    .state('parent.child', {
        url: '/child-profile/:id',
        templateUrl: 'path/to/child.html',
        resolve: {
            someId: function  ($stateParams) {
                // I cant print the id from here
                console.log("PARAMS", $stateParams.id)
                return $stateParams.id;
            }
          },
    })

Controller

.controller('lolController', 
    ['$scope', 'someId', function ($scope, someId) {

     $scope.someId = someId;

}])

But whenever i'm trying to access the url /parent/child-profile/123abc i'm getting the error Unknown provider: someId See error here..

How do I fix this? Thanks.

EDIT

The answer provided by Jay Shukla helped me get this idea.

The parameter is undefined because I declared the controller on the parent state before actually calling the child state which contains the value from it's url. Here's a simple solution I came up with, with Jay Shukla's help.

$stateProvider
    .state('parent', {
        url: '/parent',
            templateUrl: 'path/to/parent.html',
        })
    .state('parent.child', {
        url: '/child-profile/:id',
        templateUrl: 'path/to/child.html',
        controller: 'lolController'
    })

I removed the controller declaration from the parent state and moved it to the child state. Since in my situation the parent state's template only contains a <div ui-view></div>.

The idea is :

Only state is nested but both html are separate so controller models will not be inherited - Jay Shukla

Each state can have their own controller.

Please add/edit more to improve this question.


Solution

  • Try to inject $stateParams then you will get id in that object.

    Like this

    .controller('lolController', 
        ['$scope', '$stateParams', function ($scope, $stateParams) {
    
         $scope.someId = $stateParams.id;
    
    }])
    

    You can also defined your parameters in different ways as below

    url: '/child-profile/:id', // Inside stateparams you will get id as key
    OR
    url: '/child-profile/{id}',
    OR
    url: '/child-profile/:{id:int}', // Id with integer value