【问题标题】:Angularjs: How to create a optional route map param?Angularjs:如何创建可选的路线图参数?
【发布时间】:2013-11-09 22:18:13
【问题描述】:

在 AngularJS 1.1.5 上,我有两条映射路线:

 /category/:name/:article 
 
 /category/:name

我只想拥有最新的,并将参数 :article 路由到一个动作。这个动作实际上是在列表中扩展一个元素,所以我不需要重新加载控制器等,或者让我们想象在其他情况下可能是例如运行动画。例如,假设我有一个幻灯片,我想展示第 5 张幻灯片——这类事情!无需重新加载所有内容!

路线(我使用滑块示例,因为它不那么令人困惑):

.config(function(...))

$routePRovider
.when('/slider/:category', {
    templateUrl: 'slider.html',
    controller: 'sliderCtrl'
})

.when('/slider/:category/:number', {
    templateUrl: 'slider.html',
    controller: 'sliderCtrl'
});

然后在 .run() 或 .controller() 上,

scope.$on("$locationChangeStart", function(event, next, current){

        var path = $location.path();


        if((path.match("\/slider\/(.+)\/(.+)"))){ ... }; /* I'd like the 2 param to be optional, I'm still trying to find the right or correct regex for this atm. I knnow that I'll have to keep just one routemap controller, the one without the :number param */

})

经过一番研究,我找到了一个可能的解决方案:

模式

"/foo/bar/das".match("\/foo\/([^\/]+)(\/[^\/]+)?") 

返回三个参数,如果最后一个被省略,则只返回两个,但我得到额外的“/”,如 ["foo", "bar", "/das"] 和 ["foo", "bar",不明确的]。不过,我很好地处理了额外的“/”!

这个很好用:

"/foo/bar".match("\/foo\/([^\/]+)(?:\/([^\/]+))?")

重要提示

经过一些测试并找到该模式,目前看来 AngularJS 1.15 $routeProvider 并不真正支持它?我已经发布了这个,认为通过只为 /foo/:bar/:das 保留一个 routeMapper,其中第三个参数是可选的,可以作为 /foo/:bar 工作,然后在 locationChange() 上使用正则表达式。

【问题讨论】:

    标签: javascript regex angularjs angularjs-routing


    【解决方案1】:

    要使这两个参数都是可选的,您可以使用:

    var m = path.match(/issue(?:\/([^/]*))?(?:\/([^/]*))?/i);
    

    【讨论】:

    • 感谢您查看@anybhava,我将测试您的模式:) 刚刚对一个错字进行了更改,我已将“问题”更改为“滑块”或“foo”,谢谢:D
    • 当然可以使用:path.match(/slider(?:\/([^/]*))?(?:\/([^/]*))?/i);
    猜你喜欢
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 2013-07-04
    • 2010-09-07
    • 1970-01-01
    • 2012-01-19
    相关资源
    最近更新 更多