0

I'm using Angular with ui-router. I am attempting to refactor some code that looks like this:

window.location.hash = "order/" + vm.selectedRow.ID;

to this:

$state.go("^.order", {orderId: vm.selectedRow.ID} )

Changing to use $state.go handles navigating to the route just fine, however, it gets there before the URL has been updated. In the constructor for the associated controller I am grabbing an orderId from the end of the current url and using it in a query. I'm using this code:

var strings = window.location.href.split('/');
return strings[strings.length - 1];

to get the key.

Should I: 1. Continue to set window.location.hash instead of using $state.go, 2. Refactor to use $location because it lets me get to the pending URL, 3. Pass the ID value to the controller that's used by the new route?

1
  • 1
    4. use the $stateParams service to get the orderId. Commented Oct 29, 2015 at 16:58

1 Answer 1

2

If you use ui-router there is no need to use window.location in parallel. The ui-router offers a service called $stateParams which you can inject into your controller. The service provides an object that will have one key per url parameter. In your case the $stateParams object will for instance look like this:

{ orderId: 2 }

However, remember that in controllers the $stateParams object will only contain params that were registered with that state. So you will not see params registered on other states.

Another way is to use $state.params. You would simply inject $state into your controller. The advantage here is, that you can also access query params. Here is a small example:

$stateProvider.state('product', {
  url: 'product/:id/:anotherParam/?queryParam',
  controller: 'MyProductController',
});

$state.params; // Contains id, anotherParam, and also queryParam
$stateParams;  // Only contains id and anotherParam
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, since I was already injecting state, I just went with $state.params.orderId

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.