Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

URL generation for defined routes / Use routing service to both map and generate URLs #7091

@slavafomin

Description

@slavafomin

Hello, right now $routeProvider from ngRoute is used to setup routes for application.

It looks like this:

$routeProvider
    .when('/', {
        redirectTo: '/foo'
    })
    .when('/foo', {
        controller: 'FooCtrl',
        templateUrl: '/partials/foo',
    })
    .when('/foo/bar', {
        controller: 'FooBarCtrl',
        templateUrl: '/partials/foo-bar',
    })
;

And in the HTML we have to use code like this:

<a href="/foo">Foo</a>
<a href="/foo/bar">Foo's Bar</a>

The problem is, that this approach is breaking DRY principle. We have to specify URL's in two places: first in route definition when('/foo', ...) second in href attribute of HTML page. It gets complicated pretty fast when you have lots of routes and complex URLs and you trying to refactor it somehow.

The better approach is to use single service to both map and generate URLs. This service can be configured like this:

$routeProvider
    .when('root', '/', {
        redirectTo: '/foo'
    })
    .when('foo', '/foo', {
        controller: 'FooCtrl',
        templateUrl: '/partials/foo',
    })
    .when('foo-bar', '/foo/bar', {
        controller: 'FooBarCtrl',
        templateUrl: '/partials/foo-bar',
    })
;

And HTML could look like this:

<a ng-href="foo | route">Foo</a>
<a ng-href="foo-bar | route">Foo's Bar</a>

And both foo | route and foo-bar | route will be replaced by proper URLs generated with the help of routing service.

This is exactly how routing implemented in Symfony 2 framework for example.

Of course, this routing service can be implemented by the end-developers, but I think the whole community will benefit greatly if it will be included in the ngRoute. In the end, this is a good practice to keep things DRY.

Thank you! I hope I'm not duplicating issues.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions