I have this working implementation af a angularJS app which fetches some links from an URL and paint them. However the links on the URL are being updated constantly, I woul
This answer builds off of drew.walker's answer, but makes it so that changing controllers will not spawn multiple endlessly running refreshes. It also runs getData
immediately, instead of delaying it 1 second.
It depends on you using Angular routes and setting Ctrls in them. If you don't, you'll need another way to determine if this controller is in scope.
app.controller('MainCtrl', function($scope, $rootScope, $route, $timeout) {
// Function to get the data
$scope.getData = function() {
...
};
// Get the data immediately, interval function will run 1 second later
$scope.getData();
// Function to replicate setInterval using $timeout service.
$scope.intervalFunction = function() {
var currentCtrl = $route.current.$$route.controller;
var currentlyRunning = $rootScope.myAppMainCtrlRefreshRunning;
//do not run if the MainCtrl is not in scope
//do not run if we've already got another timeout underway (in case someone jumps back and forth between
//controllers without waiting 1 second between)
if (currentCtrl === "MainCtrl" && !currentlyRunning) {
$timeout(function() {
$rootScope.myAppMainCtrlRefreshRunning = true;
$scope.getData();
$scope.intervalFunction();
$rootScope.myAppMainCtrlRefreshRunning = false;
}, 1000);
};
};
// Kick off the interval
$scope.intervalFunction();
});