Raz Buchnik
Raz Buchnik

Reputation: 8411

AngularJS ui-router how to do multiple URL variants for the same state - like ngRoute when

In ngRoute you can do:

let params = {
  template: "some template"
};

$routeProvider.when("/root/cardboards/deparments", params)
.when("/suppliers/:_supplier/cardboards/deparments", params);

How to achieve the same thing using ui-router?

Upvotes: 0

Views: 179

Answers (1)

Andrew Lahikainen
Andrew Lahikainen

Reputation: 370

If you really only have two states you can do:

$stateProvider.state({
    name: 'cardboardDepartments',
    url: '/root/cardboards/departments',
    template: 'my template'
})

$stateProvider.state({
    name: 'supplierCardboardDepartments',
    url: '/suppliers/{supplierId}/cardboards/departments',
    template: 'my template'
})

Slightly more fleshed out example, assuming UiRouter > 1.0.0, using parent property (instead of parent.child name convention), and using components. You can use $stateProvider to register your routes:

$stateProvider.state({
    name: 'root',
    url: '/root',
    component: 'rootComponent'
})

$stateProvider.state({
    name: 'cardboards',
    parent: 'root',
    url: '/cardboards',
    component: 'cardboardsComponent'
})

$stateProvider.state({
    name: 'cardboardsDepartments',
    parent: 'cardboards',
    url: '/departments',
    component: 'cardboardsDepartmentsComponent'
})

$stateProvider.state({
    name: 'suppliers',
    url: '/suppliers',
    component: 'suppliersComponent'
})

$stateProvider.state({
    name: 'supplier',
    parent: 'suppliers',
    url: '/:supplierId',
    component: 'supplierComponent'
})

$stateProvider.state({
    name: 'supplierCardboards',
    parent: 'supplier',
    url: '/cardboards',
    component: 'cardboardsComponent'
})

$stateProvider.state({
    name: 'supplierCardboardsDepartments',
    parent: 'supplierCardboards',
    url: '/departments',
    component: 'cardboardsDepartmentsComponent'
})

If you do have a nested structure as shown above and you want to maintain parent-child relationships but it doesn't make sense to nest multiple ui-views you should look into named views.

If you are using controllers and templates, you can just replace the component property on these state definitions to:

controller: 'cardboardsController',
template: 'your template'

You can check out UiRouter's tutorial here. The guide is also a great resource.

Upvotes: 1

Related Questions