I have a small SPA using AngularJS (Angular1). I have a need to refresh the entire page every once in a while. The SPA gets data from REST calls, but the page refresh is to get occasional app changes. Using a "meta refresh" tag basically works, but it has a slightly annoying symptom in that it will sometimes try to refresh the page when it cannot reach the network (traveling between work and home, for instance), so it gets into an error state. It's easy enough to manually refresh the page when I'm connected, but I wish it was just a little smarter.
So, instead of the "meta refresh" tag, I defined a "HeartbeatService" factory method in my controller, and defined a method in the controller to call that method, with the intent of calling this controller method directly from a script block in my HTML page, to determine whether it's safe to reload the page or not (when my interval timer fires).
I think I'm ok with the coding in the controller, but I can't figure out how to properly obtain the scope and call the method directly from the script block.
This is my first cut at this:
<body data-ng-controller="MyController">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>
<script type="text/javascript" src="js/myMod.js"></script>
<script type="text/javascript" src="js/myApp.js"></script>
<script type="text/javascript">
window.setInterval(function() {
if (angular.element($('#MyController')).scope().heartbeat()) {
window.location.reload();
}
}, 60000)
</script>
I tried setting a breakpoint (firebug) on the "angular.element()" call, so I could experiment with calling variations of this from the console. So far, I haven't found anything that works.
Update:
The provided answer was helpful in mentioning "document.body", which meant that I didn't have to set the "id". My now working script block looks like this:
<script type="text/javascript">
window.setInterval(function() {
// Call controller method to call heartbeat service.
if (angular.element(document.body).scope().heartbeat()) {
window.location.reload();
}
}, 900000)
</script>
MyController? Seems like you forgot to add the ID...body id="MyController" data-ng-controller="MyController"- Also, why are you doing this outside your Angular controller???