How to pass array to AngularJS app via url using ui.router module

两盒软妹~` 提交于 2020-01-04 01:52:11

问题


I use Angular 1.5 and ui.router module and want to pas int array to app throw url. www.example.com/#/filter?[1,2,5] or www.example.com/#/filter/[1,2,5] or something else.

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

goal:

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

回答1:


You can't pass object through an ui-router parameter, I'd say while passing value make it , separated & then pass it.

So while calling state do something like below

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

will form below URL

www.example.com/#/filter/1,2,5

While reading it from $stateParams do split that string by ,

app.controller('catsCtrl',function($stateParams){
    console.log($stateParams.catsIds.split(','))



回答2:


As stated in the ui-router doc, one can actually pass an url parameter several time and it will be mapped as an array of values if the parameter is declared with 'array:true' in the routing configuration :

in your url :

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

will only work if your routing has :

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

See the doc for more information here : https://ui-router.github.io/ng1/docs/1.0.19/interfaces/params.paramdeclaration.html#array



来源:https://stackoverflow.com/questions/36341198/how-to-pass-array-to-angularjs-app-via-url-using-ui-router-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!