使用stateProvider angularjs的多个可选参数的Url

时间:2015-11-25 11:53:00

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

Can angularjs routes have optional parameter values?讲述 和AngularJS: Routing with URL having optional parameters 带参数名称的问号?应该使其成为可选项。它没有帮助我。

var app = angular.module('app', ['ui.router','ngRoute']);

app.config(function ($urlRouterProvider, $stateProvider) {
    $urlRouterProvider.otherwise('/a');
    $stateProvider.state('a', {
        url: '/a',
        templateUrl: 'views/a.html'
    }).state('b', {
        url: '/b/:code?/:d?',
        templateUrl : 'views/b.html'
    })
});

这个网址http://localhost:xx/kk/#/b/1/2对我来说很好。 但是http://localhost:xx/kk/#/b(没有任何参数)和http://localhost:xx/kk/#/b/1对我不起作用......

你可以看到我正在使用带有ui-router的$stateProvider。我不想切换到$urlRouteProvider

1 个答案:

答案 0 :(得分:5)

a working plunker

我们需要的是一个名为 params : {} 的设置,它可以处理可选的参数:

 params: {
    code: {squash: true, value: null},
 }

因此国家定义将是

.state('b', {
    url: '/b/:code/:d',
    templateUrl : 'views/b.html',
    params: {
      code: {squash: true, value: null},
      d   : {squash: true, value: null},
    }
})

这些将起作用:

<a href="#/b">
<a href="#/b/code1">
<a href="#/b/code22">
<a href="#/b/code333/d4">

检查这些以获取更多详细信息和示例:

还有一些神奇之处:

相关问题