【问题标题】:Conditional "otherwise" routing in AngularAngular中的条件“否则”路由
【发布时间】:2015-09-10 14:40:08
【问题描述】:

我熟悉 Angular 中的 "$urlRouterProvider.otherwise('{route here}')" 语法,可用作 Angular UI-Router 中的全部捕获。

我想知道的是 - 有没有办法根据路由输入错误时的父状态进行有条件的“否则”路由?

例如,假设我有以下配置:

$stateProvider
.state('core', {configuration here})
.state('core.page1', {configuration here...})
.state('dashboard', {configuration here})
.state('dashboard.page1', {configuration here})

$urlRouterProvider.otherwise('/core/page1');

我希望发生的是,只要输入具有 "/core/{route here}" 的路线,
如果它不匹配任何当前状态,则路由回 '/core/page1'
并且只要输入的路由具有与任何当前状态都不匹配的 "/dashboard/{route here}",就会路由回 "/dashboard/page1"

任何人都有这样做的经验,或者知道我该如何完成它? Angular 中是否有任何内置功能允许这种类型的行为?

提前致谢!

【问题讨论】:

    标签: javascript angularjs angular-ui-router


    【解决方案1】:

    如图所示

    How not to change url when show 404 error page with ui-router

    .otherwise() 不一定是字符串(url)...它可以是一个聪明的决策者:

    $urlRouterProvider.otherwise(function($injector, $location){
       var state = $injector.get('$state');
       if(....)
         state.go('core');
       else(...)
         state.go('dashboard');
       ...
       return $location.path();
    });
    

    文档:

    $urlRouterProvider.otherwise(rule)

    定义在请求无效路由时使用的路径。

    string - 您要重定向到的 url 路径或返回 url 路径的函数规则。
    function 版本传递了两个参数:$injector 和 $location services,并且必须返回一个 url 字符串。

    【讨论】:

    • 哇!感谢您的快速反应。这看起来和我要找的完全一样!仅供参考 - 您列出的链接 ($urlRouterProvider.otherwise(rule)) 不起作用。
    • 你是对的......谢谢。我修复了链接以直接访问 DOC ;)
    猜你喜欢
    • 2019-05-09
    • 2023-04-04
    • 2018-04-19
    • 2019-06-24
    • 1970-01-01
    • 2017-11-21
    • 2015-01-24
    • 2016-12-15
    • 2021-08-17
    相关资源
    最近更新 更多