developer033 developer033 - 11 months ago 40
AngularJS Question

Passing the whole object with ui-router

First of all, I'm using ui-router.

Actually I'm passing the slug through the

and it's working perfectly, as you can see below:

.state('pages', {
url: '/:slug',
template: '<page-content></page-content>'

<a ui-sref="pages({ slug: item.slug })" title="{{item.title}}" ng-repeat="item in $ctrl.menu_items">{{ item.title }}</a>

This way I can get the slug in
and in URL. However, I want to send the whole
and keep the URL with the slug.

Below you can see my attempt:

of states:

.state('pages', {
url: 'obj.slug', // -> What should I put here? (of course /:slug doesn't work anymore)
template: '<page-content></page-content>',
params: { obj: null }


<a ui-sref="pages({ obj: item })" title="{{item.title}}" ng-repeat="item in $ctrl.menu_items">{{ item.title }}</a>

It's working to passing the whole object through the states (I can get it using
), however I can't generate the URL dynamically.

An example of the

id: 6480,
title: "Test",
slug: "test"

So, the question is:

Is there a way to generate a url from a property of the
(in that way that I'm doing)? Ex: ''? (
is the slug that I want to put in the URL)

Answer Source

You can't change the URL definition once they're loaded. You'll want to do something like

.state('pages', {
    url: '/pages/:slug', // -> What should I put here?
    template: '<page-content></page-content>',
    params: { obj: null }

Then use the "slug" part to figure out where to go from there, likely from the resolve property which will allow you to inject objects into your controller.


Maybe this is more what you're looking for.

.state('pages', {
        url: '/:pageName' 
        template: '<page-content></page-content>',
        params: { obj: null }

then you change state

$state.go('pages', {pageName: item.Name, obj: item});

I'm not sure how you'd necessarily go about doing that with ui-sref on an anchor tag. Maybe this?

<a ui-sref="pages({pageName: item.Name, obj: item})"