Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularUI Router: pass url params to 'abstract' state while calling child state

I want to access the url parameter($stateParam) inside a abstract state while calling a child state. I am curious to know how that can be done. Code in plunker also

$stateProvider
    .state('contacts', {
        abstract: true,

        //my whole point is to get the id=1 here :(

        url: '/contacts/:id',
        templateUrl: function($stateParams){
            console.log("Did i get the child's parameter here? " + $stateParams.id)
            return 'contacts' + $stateParams.id + '.html'; //this will have a ui-view in it which will render its detail.
        }
    })

    .state('contacts.detail', {
        url: '/:id',
        // loaded into ui-view of parent's template
        templateUrl: 'contacts.detail.html',
        controller: function($scope, $stateParams){
          $scope.person = $scope.contacts[$stateParams.id];
        },
        onEnter: function(){
          console.log("enter contacts.detail");
        }
    })
})

`

and i call it as

<a ui-sref="contacts.detail({id: 1})">My first contact<a>

Why am I doing this way? Because, my template from the server is different for different contacts, the layout is different.

like image 587
Devaroop Avatar asked Jul 08 '14 17:07

Devaroop


2 Answers

Well, posting the issue on GitHub got me the answer from the collaborator.

So, here is the thing. The params have to be "named different" even though they are carrying the same information. Kinda weird, but works.

In the template:

<a ui-sref="contacts.detail({id: 1, duplicate_id: 1})">My first contact<a>

and in the javascript

`

$stateProvider
    .state('contacts', {
        abstract: true,

        //my whole point is to get the id=1 here :(

        url: '/contacts/:duplicate_id', //using duplicate_id here
        templateUrl: function($stateParams){} //...$stateParams will have :duplicate_id key
    }) 


    .state('contacts.detail', {
        url: '/:id', //using the real one here
        templateUrl: function($stateParams){} //....$stateParams will have :id key

    });

` UPDATE: I found that the url in this case repeats the same attribute twice which is okay for me as of now. Any suggestions welcome.

Hope this helps!

like image 181
Devaroop Avatar answered Nov 15 '22 18:11

Devaroop


This works for me:

$stateProvider
.state('contacts', {
    abstract: true,

    url: '/contacts/:id/',
    templateUrl: function($stateParams){} 
}) 


.state('contacts.detail', {
    url: 'details', 
    templateUrl: function($stateParams){}

});

So now if you want to go to contact.details and pass id which will also be available in the parent abstract state:

<a ui-sref="contacts.detail({id: 1})">My first contact<a>

and the url in your browser should be like: /contacts/1/details

like image 40
JakubM Avatar answered Nov 15 '22 18:11

JakubM