I'm trying to bind the array length from an other service to my controller scope like this:
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
});
};
});
Thats my service:
app.service('safePostService', function ($http, $timeout) {
var self = this;
var syncIntervall = 1000;
var timeoutPromise;
var sending = false;
this.queue = [];
this.post = function (url, data) {
self.queue.push({
url: url,
data: data
});
syncNow();
};
function syncNow() {
$timeout.cancel(timeoutPromise);
syncLoop();
}
function syncLoop() {
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(syncLoop, (success) ? 50 : syncIntervall);
}
}
});
The $scope.count keeps showing 0 and doesn't get updated.
Here is a fiddle: http://jsfiddle.net/kannix/CGWbq/
Angular should $watch
the safePostService.queue
.
Try:
$scope.$watch(function() { return safePostService.queue.length; }, function(item) {
$scope.count = item;
}, true);
Fiddle: http://jsfiddle.net/CGWbq/4/
You decrease the queue array in case of success :
self.queue.shift();
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments