5

Is there a way of clearing the history that Angular JS stores when a particular view is loaded through the routeProvider?

I am creating a public installation using angular and the history is going to build up a lot so I want to clear it when the home page is loaded.

Renaissance
  • 798
  • 5
  • 15
user2424495
  • 573
  • 1
  • 6
  • 19

4 Answers4

10

in your Controller inject $scope and $location.

$scope.$on('$viewContentLoaded', function(){
  //view loaded do some stuff.
    $location.replace(); //clear last history route
});
schwertfisch
  • 4,549
  • 1
  • 19
  • 32
0

Within the controller I added a function to change the view:

$scope.changeView = function(view) {
    $location.path(view);
    $location.replace();
}

Then within the view I added an ng-click to call this function:

<div ng-click="changeView('/app/new_view')">

From the angular Docs $location.replace() method is used to replace the topmost view in the history stack, instead of adding a new one.

There is a special replace method which can be used to tell the $location service that the next time the $location service is synced with the browser, the last history record should be replaced instead of creating a new one.

Reference: https://docs.angularjs.org/guide/$location

Kailas
  • 7,350
  • 3
  • 47
  • 63
user2424495
  • 573
  • 1
  • 6
  • 19
  • That is not what this code does. Instead, it loads the new view and adds it to history, replacing the last element in the history. – Blake Miller Apr 12 '14 at 22:16
0
 for(var a=0; a < $rootScope.$viewHistory.histories.root.stack.length; a++ ){
         console.log(" for history remove " + a );
         delete $rootScope.$viewHistory.histories.root.stack[a];
     }
  • Code is good, but a plain-English explanation can't hurt. See [How do I write a good answer?](http://stackoverflow.com/help/how-to-answer) – jub0bs Oct 18 '14 at 11:39
  • 2
    `$rootScope.$viewHistory` is undefined. It is something which you are adding to `$rootScope` or angular provides it. – Hitesh Kumar Jul 31 '15 at 09:27
0
var dummyState = {app: 'resto'};

// set up history state
if (!$window.history.state) {
  $window.history.pushState(dummyState, '');
}

// when history back
$window.onpopstate = function() {
  console.log('window.onpopstate:url=', $window.location.href);
  console.log('window.onpopstate:history.state=', $window.history.state);

  // repopulate history state so we get the popstate event again
  $window.history.pushState(dummyState, '');
};