我正在尝试将数组长度从其他服务绑定到我的控制器范围,如下所示:
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
});
};
});
这就是我的服务:
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);
}
}
});
$ scope.count保持显示0并且不会更新。
这是一个小提琴: http://jsfiddle.net/kannix/CGWbq/
答案 0 :(得分:5)
Angular应该$watch
safePostService.queue
。
尝试:
$scope.$watch(function() { return safePostService.queue.length; }, function(item) {
$scope.count = item;
}, true);
小提琴: http://jsfiddle.net/CGWbq/4/
如果成功,您将减少队列数组:
self.queue.shift();