I would like to reset the state of my angular app without forcing a page refresh. What's the idiomatic way to do this?
-
2Have you tried stackoverflow.com/questions/16703215/…?Blackhole– Blackhole2014-05-31 19:04:52 +00:00Commented 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.JeffryHouser– JeffryHouser2014-05-31 19:15:47 +00:00Commented 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.event_jr– event_jr2014-05-31 19:40:58 +00:00Commented May 31, 2014 at 19:40
Add a comment
|
1 Answer
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/
2 Comments
Ian Walter
This doesn't work and the fiddle no longer contains the same code.
nickolay.laptev
I did all 3 points but got an error that element was already bootstrapped.