本文介绍了用于类似 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 问题(从 这个问题) 但我想知道是否有解决方案或首选解决方案.

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 正则表达式路由以加载不同的控制器和视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 17:49