加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 18:03:32 所属栏目:安全 来源:网络整理
导读:我正在尝试使用可选参数创建路由;显然ui.route没有这种能力(即使ngRoute几乎永远存在).所以相反,我已将它们指定为查询参数,并尝试将它们转换为适当的RESTful网址,该网址将针对$stateParams展开: 在ngRouter语法中,我将指定:/:resource /:collection?/:
我正在尝试使用可选参数创建路由;显然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以获取更多详细信息.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读