angular-ui – 使用可选参数进行动态路由时,AngularUI urlRouterProvider

前端之家收集整理的这篇文章主要介绍了angular-ui – 使用可选参数进行动态路由时,AngularUI urlRouterProvider前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用可选参数创建路由;显然ui.route没有这种能力(即使ngRoute几乎永远存在).所以相反,我已将它们指定为查询参数,并尝试将它们转换为适当的RESTful网址,该网址将针对$stateParams展开:

在ngRouter语法中,我将指定:/:resource /:collection?/:type?/:index?

在ui.router中,我将其指定为:/:resource?collection& type& index

我试图用一个返回路径的函数动态地翻译它(尝试使用.when()和.rule()):

$urlRouterProvider
.when('','/index')
.when('/','/index')
.when( urlMatcher.source,function convertToREST( $match,$stateParams )
{
    var params = [$match.resource];
    if ( angular.isDefined($match.collection) ) params[1] = $match.collection;
    if ( angular.isDefined($match.type) )       params[2] = $match.type;
    if ( angular.isDefined($match.index) )      params[3] = $match.index;
    var result = '/' + params.join('/');
    return result;
} )
.otherwise( '/404' );

上面导致没有渲染视图(删除第3 .when()和视图渲染就好了).

并手动:

$urlRouterProvider
.when('','/index')
.when( '/:resource?collection','/:resource/:collection' )
.otherwise( '/404' );

这显然导致循环迭代.我从ui-router的示例应用程序中得到了这个手册的想法:state.js#L16.我看到的唯一区别是我的参数开始,但我不明白这有什么关系.

解决方法

如果我正确理解了这个问题,那么你想要实现的是你网址的可选参数.

ui.router确实提供了此功能,有几个选项可用于指定参数.基本参数如下所示:

$stateProvider
    .state('contacts.detail',{
        url: "/contacts/:contactId",templateUrl: 'contacts.detail.html',controller: function ($stateParams) {
            // If we got here from a url of /contacts/42
            expect($stateParams).toBe({contactId: "42"});
        }
    })
Alternatively you can also use curly brackets:

// identical to prevIoUs example
url: "/contacts/{contactId}"

如果要嵌套状态,则必须解析父路径中的参数,文档中提供了类似的情况:

$stateProvider.state('contacts.detail',{
   url: '/contacts/:contactId',controller: function($stateParams){
      $stateParams.contactId  //*** Exists! ***//
   }
}).state('contacts.detail.subitem',{
   url: '/item/:itemId',controller: function($stateParams){
      $stateParams.contactId //*** Watch Out! DOESN'T EXIST!! ***//
      $stateParams.itemId //*** Exists! ***//  
   }
})

解决方案是在父路由中使用resolve语句

$stateProvider.state('contacts.detail',controller: function($stateParams){
      $stateParams.contactId  //*** Exists! ***//
   },resolve:{
      contactId: ['$stateParams',function($stateParams){
          return $stateParams.contactId;
      }]
   }
}).state('contacts.detail.subitem',controller: function($stateParams,contactId){
      contactId //*** Exists! ***//
      $stateParams.itemId //*** Exists! ***//  
   }
})

如图所示,通过在控制器中使用$stateParams来获取结果

$stateParams.contactId

您可以参考documentation获取更多详细信息.

猜你在找的Angularjs相关文章