Another Better Solution: A better solution is to use the $interval
service within your controller and periodically refresh the data in your ViewModel.
For example, the following controller will initially load the list of Users
known to the system, and then every 3 seconds refresh that list making it available
through the controller:
app.controller('UserListController', [ '$http', '$scope', '$interval', 'authentication',
function UserListController($http, $scope, $interval, authentication) {
var vm = this;
vm.pageHeader = {
title: 'User List'
};
// Initially gets list of users
getAllUsers($http)
.success(function(data) {
vm.users = data;
vm.message = "Users list found!";
})
.error(function (e) {
vm.message = "Could not get list of users";
});
// Refreshes lists of users periodically
$scope.callAtInterval = function() {
console.log("Interval occurred");
getAllUsers($http)
.success(function(data) {
vm.users = data;
vm.message = "Users list found!";
})
.error(function (e) {
vm.message = "Could not get list of users";
});
}
$interval( function(){$scope.callAtInterval();}, 3000, 0, true);
}]);
Notes:
- Any elements on the page that display the objects from the
vm.users
array of objects will automatically be updated when the interval occurs and
there is new or changed data.
- Care should be taken not to make the interval period too short, and it should
be based on the responsiveness and data refresh needs of your application. For
example, an interactive two player game might want to refresh its data every
second or two in order to detect any player movements and present an appealing
player experience, while a "status monitoring console" that displays system status graphically may only need to refresh its data every 20 or 30 seconds.
- A good documentation source for
$interval is
here.