1

I wonder how a parameters values in a state (angular-ui-router) to be an array.

1) State

.state('products-by-category', {
   url: "/rent-designer-category/{price_range:int}",
   params: {
       price_range: { array: true }
   }
})

2) Controller

var urlParams = ['bt',1,150]; 
$state.transitionTo('products-by-category', urlParams, {
    location: true,
    inherit: true,
    relative: $state.$current,
    notify: false
});

3) URL on browser

http://localhost:3000/rent-designer-bags/?price_range=bt&price_range=1&price_range=150

What i want the URL to be is :

http://localhost:3000/rent-designer-bags/?price_range=['bt',1,150]

Any idea how i can achieve this ? Is that possible ?

2

1 Answer 1

2

It is as simple as you think:

.state('products-by-category', {
  params: {
    priceRange: null
  }
})

Your code in the controller:

var urlParams = ['bt', 1, 150]; 
$state.go('products-by-category', { priceRange: urlParams });

Don't use transitionTo, as you don't need to. The $state.go() does just fine. Your second argument needed changing, as you have to pass the name of the param you want with the array you had set up as the value for it. You had a third argument to $state.go() which isn't really needed as the options are mostly all default.

You've also written the url for a direct call. You don't really need this, if you're already using the router to move around ($state.go for example). No user is going to be writing in such a url unless they know angularjs/ui-router inside and out and even then it's somewhat unlikely.

Edit: Updating the answer. If you want to access the array on the 'other side', in the controller, you'd access it via $stateParams:

export default class someClass() {
  constructor($stateParams) {
    super(arguments);

    this.priceRange = this.$stateParams.priceRange;
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I've tried it & it didn't work. it displayed the same url as url above.
If you're using ui-router, the question still remains, what do you need the url for? A SPA shouldn't need the user to know any url other than the first opening page, everything from there should be handled by ui-router. What are you trying to achieve by wanting/having the array values in the url?
i want to retrieve data from api with that params
So in the controller, you'll have several injections into the constructor. One of those will be $stateParams, if you want to access the resolve's data, you can to it via $stateParams.priceRange - that'll be the data you passed via the resolve.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.