Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With angularjs and ui-router, how to disable the navigator history for one view change

I want the current state change not to be saved in navigation history. Then when user clicks 'back', the view will be skipped and go back to previous page.

Can I temporally disable the state change to be saved in navigator history?

like image 752
Mavlarn Avatar asked Jun 15 '14 17:06

Mavlarn


2 Answers

I believe this where ui-router's option parameter with value { location:'replace'} is intended for.

The documentation explains:

location Boolean or "replace" (default true), If true will update the url in the location bar, if false will not. If string "replace", will update url and also replace last history record.

It seems that there's an issue (see it here on GitHub) to be fixed though.

like image 122
EeKay Avatar answered Sep 20 '22 12:09

EeKay


In the spirit of stackoverflow I will try to answer the question and not mention that what you are asking for is a truly horrible hack ;-)

I think you may need something like this. (the code is coffeescript)

angular
.module 'app', ['ui.router']
.run ($rootScope, $state) ->
    $rootScope.$on '$locationChangeStart', (event) =>
        if $state.is 'bad-state'
            event.preventDefault()
            $state.go 'good-state'

When the location changes (you could also use $stateChangeStart) you check the current state and if it is the state you don't want then you go to the state you do want. the event.preventDefault() effectively halts the processing of the originally requested state.

If you need an even dirtier version then you could check the location urls instead of the states and use $location.url to perform the transfer, like this:

angular
.module 'app', ['ui.router']
.run ($rootScope, $location) ->
    $rootScope.$on '$locationChangeStart', (event, nextLocation) =>
        if nextLocation is '/bad/location'
            event.preventDefault()
            $location.path '/good/location'
like image 38
biofractal Avatar answered Sep 19 '22 12:09

biofractal