I would like to reset the state of my angular app without forcing a page refresh. What's the idiomatic way to do this?
            Asked
            
        
        
            Active
            
        
            Viewed 1.0k times
        
    14
            
            
        - 
                    2Have you tried http://stackoverflow.com/questions/16703215/how-to-reload-or-re-render-the-entire-page-using-angularjs? – Blackhole May 31 '14 at 19:04
- 
                    What state do you want to reset? In one application I built; we provided each screen/aspect of the app a reset method which would reset the state of the view. When the user logged out; we would 'reset' all the views and load the login screen. Tedious, but functional. In another app I built; we forced a reload of the app. Much easier; but not as elegant. – JeffryHouser May 31 '14 at 19:15
- 
                    1@JeffryHouser I want to reset all state. As if when the page was reloaded. I understand reloading the route forces the view to rerender, and create new instances of related controllers. I'm interested in resetting all services as well. – event_jr May 31 '14 at 19:40
1 Answers
11
            
            
        I don't know if there's an idiomatic way, but if you use manual bootstrap (ie, get rid of ng-app), then to reset you could
- Remove the element that you bootstrapped angular into
- Replace it with a clean copy of the element
- Run bootstrap again
Example HTML:
<div id="myid" ng-controller="MyCtrl">
  <button ng-click="i = i+1">Add 1</button>
  <span>i = {{i}}</span>
  <button ng-click="reset()">RESET</button>
</div>
Example controller/JS (with jQuery included as well), which would be run on onload:
var $cleanCopy = $("#myid").clone();
function bootstrap() {
  angular.bootstrap(document.getElementById('myid'), ['mymodule']);
}
angular.module('mymodule', []).controller('MyCtrl', function($scope) {
  $scope.i = 1; 
  $scope.reset = function() {
    // You need this second clone or angular bootstraps
    // into the original clone!
    $("#myid").replaceWith($cleanCopy.clone());
    bootstrap();
  };
});
bootstrap();
Here is a working JSFiddle: http://jsfiddle.net/zd377/2/
 
    
    
        mgnb
        
- 2,803
- 2
- 16
- 15
- 
                    
- 
                    I did all 3 points but got an error that element was already bootstrapped. – nickolay.laptev Oct 30 '16 at 14:03
