Let's get to the important details: When I link a $scope variable in my controller directly to a $resource, Angular takes care of promise resolution automatically and updates my view as soon as data is received from the service. However, I need to periodically check for updates from the server. Trying to bind to the promise returned by the $interval function does not trigger Angular's automatic promise resolution, and I'm unsure of how to make $interval work with a $resource.
My setup involves an Angular client, ASP.NET WebApi serving JSON, and Angular $resource interfacing with WebApi. When I connect a $scoped variable to my $resource promises within the Angular controller, it works fine; however, I face challenges when attempting to update these resources at intervals using $interval.
The code snippet that works but requires manual refreshing (relevant excerpt):
'use strict';
var ctrls = angular.module('MyModule',[]);
ctrls.controller('FooCtrl', ['$scope', '$location','service',
function( $scope,$location,service)
{
$scope.Bars = service.Bars;
$scope.Baz = service.Baz;
}
var app = angular.module('MyModule.Services',['ngResource']);
app.service('service', ['$resource', function($resource)
{
var proxy = $resource(
'http://server/subsystem/api/Foo/:component',
{},
{
Bars: {method:'GET',isArray:false,url: 'http://server/subsystem/api/Foo/Bars'},
Baz: {method:'GET',isArray:false,rul: 'http://server/subsystem/api/Foo/Baz'}
}
return proxy;
}]);
blah blah blah, using ng-repeat in my view bound to "bar in Bars" displays data on screen.
Now, when I try to implement the interval in my controller, the promise doesn't resolve correctly.
Changes inside the controller (added $interval and $document to dependencies list):
var stop;
$scope.Bars = {};
$scope.Baz = service.Baz; //Angular resolves this promise automatically.
$scope.pollService = function(){
if(angular.isDefined(stop))return;
stop = $interval(function(){
if(service){
$scope.Bars = service.Bars;
}
},1000);
};
$scope.stopPolling = function(){
if(angular.isDefined(stop)){
$interval.cancel(stop);
stop = undefined;
}
};
$scope.$on('$destroy',function(){
$scope.stopPolling();
});
$document.ready(function(){
$scope.pollService();
});
Edit
The issue I'm facing is that binding $scope.Bars directly to service.Bars triggers Angular's automatic promise resolution, but adding the $interval call seems to be problematic. Checking $scope.Bars in Chrome Dev Tools shows that it remains an unresolved promise.
I have updated my sample code to reflect what I'm currently debugging. There are several properties defined on my resource, including one named 'Baz'. If I assign $scope.Baz = service.Baz directly in my controller, the view binds to it once Angular resolves the promise, whereas the one triggered by the interval does not.