I am attempting to connect the length of an array from another service to my controller's scope in the following manner:
app.controller('TestCtrl', function ($scope, safePostService) {
$scope.count = safePostService.queue.length;
$scope.addOne = function () {
safePostService.post('/echo/json/', {
json: JSON.stringify({
text: 'some text',
array: [1, 2, 'three'],
object: {
par1: 'another text',
par2: [3, 2, 'one'],
par3: {}
}
}),
delay: 3
});
};
});
This is my service:
app.service('safePostService', function ($http, $timeout) {
var self = this;
var syncInterval = 1000;
var timeoutPromise;
var sending = false;
this.queue = [];
this.post = function (url, data) {
self.queue.push({
url: url,
data: data
});
synchronizeNow();
};
function synchronizeNow() {
$timeout.cancel(timeoutPromise);
synchronizeLoop();
}
function synchronizeLoop() {
if (sending) return;
sending = true;
var item = self.queue[0];
$http.post(item.url, item.data).
success(function () {
self.queue.shift();
afterResponse(true);
}).
error(function () {
afterResponse(false)
});
}
function afterResponse(success) {
sending = false;
if (self.queue.length > 0) {
timeoutPromise = $timeout(synchronizeLoop, (success) ? 50 : syncInterval);
}
}
});
The $scope.count continues to display as 0 and does not update.
Check out this fiddle: http://jsfiddle.net/kannix/CGWbq/