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

时间:2014-05-23 13:23:45

标签: angularjs angular-ui angular-ui-router

我正在尝试使用ui-router找到在Angular.js中实现路由别名的方法。

假设我的状态包含网址article/:articleId,我希望/articles/some-article-title/article/76554重定向到ui-router而不更改浏览器位置。

可以使用{{1}}完成吗?

1 个答案:

答案 0 :(得分:13)

予。双重状态映射(重用控制器,视图)

注意:这是原始答案,显示了如何解决两个状态的问题。以下是另一种方法,根据Geert

对评论做出反应

plunker个工作示例。假设我们有两个对象(在服务器上)

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',},
];

我们希望将URL用作

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

// by Title
../article/The-cool-one
../article/The-poor-one

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

// 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;
    }],
  })

正如我们所看到的,诀窍是控制器模板 (templateUrl)是相同的。我们只是向服务ArticleSvc询问getById()getByTitle()。解决后,我们可以使用返回的项目......

具有更多详细信息的plunker是here

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

注意:此扩展程序会对Geert相应的评论

做出反应

因此,路由别名有UI-Router内置/本机方式。它被称为

$urlRouterProvider - .when()

我创建了工作plunker here。首先,我们只需要一个状态定义,但对ID没有任何限制。

.state('articles.detail', {
    //url: "/{ID:[0-9]{1,8}}",
    url: "/{ID}",

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

var getIdByTitle = function(title){
   // some how get the ID for a Title
   ...
}

现在是$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;
  }
);

那就是它。这个简单的实现会跳过错误,错误的标题......处理。但预计无论如何都要实施...... Check it here in action