如何使用ui.router模块通过url将数组传递给AngularJS应用程序

时间:2016-03-31 18:41:29

标签: angularjs angular-ui-router

我使用Angular 1.5和ui.router模块,并希望将int数组传递给app throw url。 www.example.com/#/filter?[1,2,5]或www.example.com/#/filter/[1,2,5]或其他内容。

.state('cats', {
             url: '/filter?catsIds', // or /filter/{catsIds}
             templateUrl:'cats.html',
             controller: 'catsCtrl'
         })

目标:

app.controller('catsCtrl',function($stateParams){
    console.log(Array.isArray($stateParams.catsIds)) // goal true
    ...

2 个答案:

答案 0 :(得分:7)

你不能通过ui-router参数传递对象,我会说在传递值的同时使它,分开&然后通过它。

因此,在调用州时,请执行以下操作

$state.go('cats', { catsIds: [1,2,5].join(',') })

将在URL

下面形成
www.example.com/#/filter/1,2,5

$stateParams读取时,请按,

拆分该字符串
app.controller('catsCtrl',function($stateParams){
    console.log($stateParams.catsIds.split(','))

答案 1 :(得分:0)

如ui-router文档中所述,实际上可以多次传递一个url参数,如果在路由配置中使用'array:true'声明该参数,它将被映射为值数组:

在您的网址中:

www.example.com/#/filter?catsIds=1&catsIds=2&catsIds=5

仅在您的路由具有以下功能时可用:

{
  name: 'foo',
  url: '/foo/{arrayParam:int}`,
  params: {
    arrayParam: { array: true }
  }
}

有关更多信息,请参见文档:https://ui-router.github.io/ng1/docs/1.0.19/interfaces/params.paramdeclaration.html#array