Last active
May 19, 2022 15:06
-
-
Save statico/db8267164ebdd163f587 to your computer and use it in GitHub Desktop.
demo of hot-reloading/replacing angularjs modules
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<title>angular test</title> | |
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.js"></script> | |
</head> | |
<body> | |
<h3>demo of reloading/replacing angularjs modules</h3> | |
<div id="content" ng-controller="FooCtrl">value = {{ value }}</div> | |
<script> | |
// nothing new here! | |
angular | |
.module('myapp', []) | |
.controller('FooCtrl', function($scope) { $scope.value = 'one'; }); | |
angular.bootstrap(document.getElementById('content'), ['myapp']); | |
// -------------------------------------------------- | |
// for profiling purposes | |
for (var i = 0; i < 100; i++) { | |
(function(i) { | |
// delete the old element and angular scope hoping that GC will clean up after me | |
// see: http://stackoverflow.com/a/22066098/102704 | |
var el = document.getElementById('content'); | |
el.parentNode.removeChild(el); | |
angular.element(el).injector().get('$rootScope').$destroy(); | |
// create the new element | |
el = document.createElement('div'); | |
el.id = 'content'; | |
el.innerText = 'value = {{ value }} (replaced)'; | |
el.setAttribute('ng-controller', 'FooCtrl'); | |
document.body.appendChild(el); | |
// create the replacement controller (no errors as of 1.3.x) | |
angular | |
.module('myapp', []) | |
.controller('FooCtrl', function($scope) { $scope.value = i; }); | |
// bootstrap again | |
angular.bootstrap(document.getElementById('content'), ['myapp']); | |
})(i); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment