MOLEDesign MOLEDesign - 12 days ago 5
AngularJS Question

Utilising $scope.apply()

I have the following which works fine, drawing info from a RESTful api feed

app.controller('servicesController', ['$scope', '$location', '$http', '$interval',
function($scope, $location, $http, $interval) {

var getData = function() {

// Initialize $scope using the value of the model attribute, e.g.,
$scope.url = "https://(remote link to JSON api)";

$http.get($scope.url).success(function(data) {
$scope.listOfServices = data.runningServices; // get data from json
});

};

getData();
$interval(getData(), 10000);
}
]);


However my view is not updating every 10 seconds as expected. I have read that I need to use $scope.apply() somewhere in this above code.

I tried placing the following (in the appropriate place above)

$http.get($scope.url).success(function(data) {
$scope.listOfServices = data.runningServices; // get data from json
$scope.apply(); //I also tried $scope.runningServices.apply()
});

Answer

$scope.apply is not your problem, the scope will be digested automatically at the end of the $http request and $interval. Certain actions automatically "inform" Angular that the scope may have changed and trigger a digest; only if you're writing "non-Angular" code may you have to explicitly trigger a scope digest, since otherwise Angular wouldn't notice any changes.

No, your issue is that you're calling getData(), and then have its return value (undefined) execute every ten seconds. Which is obviously nonsense. You just want to pass the function itself to $interval:

$interval(getData, 10000);
// look ma, ^^^^^, no parentheses