14

I would like to reset the state of my angular app without forcing a page refresh. What's the idiomatic way to do this?

3
  • 2
    Have you tried stackoverflow.com/questions/16703215/…? Commented May 31, 2014 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. Commented May 31, 2014 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. Commented May 31, 2014 at 19:40

1 Answer 1

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

  1. Remove the element that you bootstrapped angular into
  2. Replace it with a clean copy of the element
  3. 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/

Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't work and the fiddle no longer contains the same code.
I did all 3 points but got an error that element was already bootstrapped.

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.