用于加载不同控制器和视图的类似 url 的 AngularJS 正则表达式路由 [英] AngularJS regex route for similar url to load different controller and view

查看:23
本文介绍了用于加载不同控制器和视图的类似 url 的 AngularJS 正则表达式路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的路由,它应该根据参数是否为数字来加载不同的视图和控制器.示例:

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 应该 ArtistsIndexController 带有视图 /www/artists/index.html
  • /artists/name 应该 ArtistsProfileController 带有视图 /www/artists/profile.html
  • /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"
});

其中 :page 是一个数字,而 :name 不是.

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

注意我看到了一个相关的 github 问题(从 this question) 但我想知道是否有解决方案或首选解决方案.

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

推荐答案

另一种方法是使用 ui-router 支持路由的正则表达式(在许多其他事物中),这将允许:

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"
});

这篇关于用于加载不同控制器和视图的类似 url 的 AngularJS 正则表达式路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆