Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restart angular app without page reload?

Tags:

angularjs

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

like image 861
event_jr Avatar asked May 31 '14 18:05

event_jr


1 Answers

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/

like image 173
mgnb Avatar answered Oct 02 '22 23:10

mgnb