I know there are some similar questions, but I haven't had success with any of the answers, none of the situations seem exactly similar. I am quite new to Angular and I know the whole process here isn't optimal but I feel like I'm close to getting at least a working prototype to refine:
I am trying to create an app that executes scripts on a schedule on the server, so in the background we have the following code which sends a request to run all of the files scheduled to run every 5 seconds. The scripts execute and a mongo database is updated - each "test" has an array of "results". Each time the script is executed, a new "result" is created and pushed to test.results array.
var interval = 5000;
setInterval(function() {
request.get(
'http://localhost:3000/tests/run/5000',
function (error, response, body) {
if (error) { return next(err) }
}
);
}, interval);
On the Angular side, there is a page that displays all of the results in test.results. When the page first loads, it looks up the current test and we have it as state param:
// The apps state, displays the selected "test", and lists results for the test.
.state('tests', {
url: '/tests/{id}',
templateUrl: '/tests.html',
controller: 'TestsCtrl',
resolve: {
test: ['$stateParams', 'tests', function($stateParams, tests) {
return tests.get($stateParams.id);
}]
}
})
The view is rendered:
<script type="text/ng-template" id="/tests.html">
<div class="page-header">
<h1>{{test.name}} | Results</h1>
</div>
<div ng-repeat="result in test.results">
<h4>{{result.timestamp}} | <span ng-class="result.passed"}">{{result.passed}}</span></h4>
<h5>Output:</h5>
<p style="white-space: pre;">{{result.output}}</p> <!--white-space:pre to preserve formatting (ie \n's)-->
<h5 style="color:red";>Errors:</h5>
<p style="white-space: pre;">{{result.error}}</p>
</div>
<!-- ... -->
All of this works well enough except that I can't get the view to update without manually refreshing the page. For now I am just trying to create a similar timer in the controller which reloads the test parameter on a schedule. (ie for now it doesnt matter if the update occurs exactly when the new result is added, I just want the view to update periodically with new tests.) The closest I've gotten seems to be something like:
angular.module('syntinel')
.controller('TestsCtrl', [
'$scope',
'tests',
'test',
'auth',
'$interval',
function($scope, tests, test, auth, $interval){
$scope.test = test;
$scope.isLoggedIn = auth.isLoggedIn;
$scope.runTest = function(){
tests.run(test);
};
// How to get scope to refresh?
$interval( function(){
$scope.test = tests.get(test._id);
}, 3000);
}]);
So I'm trying to just do a new get request to retrieve the latest data from the db, which should contain any newly added 'results'. I don't get any errors, but the current list of results being display goes away and I have no data being displayed in the view once this code runs.
Any help is appreciated.