17
votes

I am wondering how to "reload" a current state, passing in a new parameter so that my controller gets re-initialized.

I am trying to implement a search in my sidebar control - and the initial search uses $state.go to transition to my new state like this:

if ($event.type === 'click' || $event.keyCode === keyCodes.enter) {
     $state.go("people.search", { search: vm.searchText });

If I am on another state in the application, and the above code runs, everything works correctly. So, I pass in the search term as a parameter and $state.go transitions my state to the people.search state and my people controller (containing the search function) gets hit. But once I am on the people.search state and try to use the search control, the people controller code does not get hit anymore and the parameters are not getting updated.

I tried modifying the code to this:

$state.go("people.search", { search: vm.searchText }, { location: "replace" });

Now when I am on the current state, this will update the url with my new search term, but the controller code is not firing.

I need a way to force a reload of the same state that I am currently on, so that the new search parameter gets updated and the people controller code re-runs.

How do I reload the current state?

4

4 Answers

14
votes

Inside javascript You can call current state like so:

$state.go ('.', { search: vm.searchText } )

As of version 1.2.5 you can also use just reload the state:

$state.reload()

That's all nice, but I prefer a way to reload state with different params within a directive. So I looked inside ui-router source code just to understand that uiSref directive is ignored when the state remains the same. While it is nice to prevent reloading if nothing really changed, changing params inside the state could be useful in some cases.

So I created my own directive uiSrefParams: https://gist.github.com/IlanFrumer/8281567

Example

<span>Change language:</span>
<a ui-sref-params="{lang: 'en'}">english</a>
<a ui-sref-params="{lang: 'ru'}">russian</a>

Hope that helps.

10
votes

try this

$state.go($state.current, {}, {reload: true});
2
votes

Do note as of 0.2.14 you also have an option to just reload the current state and not it's parent.

So $state.go(people.search, {}, {reload: true}); would reload the people state as well as all its childs.

While $state.go(people.search, {}, {reload: "people.search"}); would not reload the people state but would reload people.search and its childs.

0
votes

Also note that your state should have ?param at the end to make this solution work. I've got caught on this, because $location.search() work without it.