如何在ui-router中实现路径别名

Cas*_*yne 11 angularjs angular-ui angular-ui-router

我正试图找到一种方法来实现Angular.js中的路由别名ui-router.

假设我有一个带url的状态,article/:articleId我想/articles/some-article-title/article/76554不改变浏览器位置的情况下重定向(内部).

可以这样做ui-router吗?

Rad*_*ler 14

I.双重状态映射(控制器,视图的重用)

注意:这是原始答案,显示如何解决两个状态的问题.以下是另一种方法,对Geert的评论做出反应

有一个带有工作实例的龙头.假设我们有这两个对象(在服务器上)

var articles = [
  {ID: 1, Title : 'The cool one', Content : 'The content of the cool one',},
  {ID: 2, Title : 'The poor one', Content : 'The content of the poor one',},
];
Run Code Online (Sandbox Code Playgroud)

我们想用URL作为

// by ID
../article/1
../article/2

// by Title
../article/The-cool-one
../article/The-poor-one
Run Code Online (Sandbox Code Playgroud)

然后我们可以创建这个状态定义:

// the detail state with ID
.state('articles.detail', {
    url: "/{ID:[0-9]{1,8}}",
    templateUrl: 'article.tpl.html',
    resolve : {
      item : function(ArticleSvc, $stateParams) {

        return ArticleSvc.getById($stateParams.ID);
      },
    },
    controller:['$scope','$state','item',
      function ( $scope , $state , item){ 

        $scope.article = item;
    }],
  })

// the title state, expecting the Title to be passed
.state('articles.title', {
    url: "/{Title:[0-9a-zA-Z\-]*}",
    templateUrl: 'article.tpl.html',
    resolve : {
      item : function(ArticleSvc, $stateParams) {

        return ArticleSvc.getByTitle($stateParams.Title);
      },
    },
    controller:['$scope','$state','item',
      function ( $scope , $state , item){ 

        $scope.article = item;
    }],
  })
Run Code Online (Sandbox Code Playgroud)

我们可以看到,诀窍是ControllerTemplate (templateUrl)是相同的.我们只是要求服务ArticleSvcgetById()getByTitle().解决后,我们可以使用返回的项目...

更多细节plunker是这里

II.别名,基于本机UI-Router功能

注意:此扩展对Geert适当的评论作出反应

因此,有UI-Router一种用于路由别名的内置/本机方式.它被称为

$ urlRouterProvider - .when()

我在这里创造了工作的plunker.首先,我们只需要一个州定义,但对ID没有任何限制.

.state('articles.detail', {
    //url: "/{ID:[0-9]{1,8}}",
    url: "/{ID}",
Run Code Online (Sandbox Code Playgroud)

我们还必须实现一些mapper,将title转换为id (别名映射器).这将是新的文章服务方法:

var getIdByTitle = function(title){
   // some how get the ID for a Title
   ...
}
Run Code Online (Sandbox Code Playgroud)

而现在的力量 $urlRouterProvider.when()

 $urlRouterProvider.when(/article\/[a-zA-Z\-]+/,
  function($match, $state, ArticleSvc) {

    // get the Title 
    var title = $match.input.split('article/')[1];
    // get some promise resolving that title
    // converting it into ID
    var promiseId = ArticleSvc.getIdByTitle(title);

    promiseId.then(function(id){

      // once ID is recieved... we can go to the detail
      $state.go('articles.detail', { ID: id}, {location: false}); 
    })

    // essential part! this will instruct UI-Router, 
    // that we did it... no need to resolve state anymore
    return true;
  }
);
Run Code Online (Sandbox Code Playgroud)

而已.这个简单的实现会跳过错误,错误的标题......处理.但预计无论如何都会实现...... 请在此处查看

  • 这不是任何类型的别名,只是两个看起来非常相似的状态配置(并且实际上重用了相同的模板) (4认同)