Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS regex route for similar url to load different controller and view

I have a similar route that should load a different view and controller based on whether or not the parameter is a number. Example:

  • /artists/2 should ArtistsIndexController with a view /www/artists/index.html
  • /artists/name should ArtistsProfileController with a view /www/artists/profile.html

Ideally I would use something like:

$routeProvider.when("/artists/:page", {
  templateUrl: "/www/artists/index.html",
  controller: "ArtistsIndexController"
});

$routeProvider.when("/artists/:name", {
  templateUrl: "/www/artists/profile.html",
  controller: "ArtistsProfileController"
});

Where :page is a number and :name is not.

Note I see a related github issue (found from this question) but am wondering if there is a resolution or preferred solution.

like image 241
Gloopy Avatar asked Aug 08 '13 17:08

Gloopy


2 Answers

Another way is to use the ui-router which supports regular expressions for routes (among a slew of other things) which would allow:

$stateProvider.state("artists-index", {
  url: "/artists/{page:[0-9]*}",
  templateUrl: "/www/artists/index.html",
  controller: "ArtistsIndexController"
});

$stateProvider.state("artists-profile", {
  url: "/artists/{name}",
  templateUrl: "/www/artists/profile.html",
  controller: "ArtistsProfileController"
});
like image 196
Gloopy Avatar answered Nov 03 '22 02:11

Gloopy


I use a nasty hack, that consist on change the regexp

var $route = $routeProvider.$get[$routeProvider.$get.length-1]({$on:function(){}});


$routeProvider.when("/artists/:page", {
  templateUrl: "/www/artists/index.html",
  controller: "ArtistsIndexController"
});

$routeProvider.when("/artists/:name", {
  templateUrl: "/www/artists/profile.html",
  controller: "ArtistsProfileController"
});

$route.routes['/artist/:page'].regexp = /^\/(?:artist\/(\d+))$/
$route.routes['/artist/:page/'].regexp = /^\/(?:artist\/(\d+))\/$/

It's ugly but it works fine. You can change your routes' regexps to make them match whatever you want.

like image 3
pykiss Avatar answered Nov 03 '22 00:11

pykiss