gpt4 book ai didi

javascript - angularjs 将服务数组长度属性绑定(bind)到 Controller 范围

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:06:15 26 4
gpt4 key购买 nike

我正在尝试将来自其他服务的数组长度绑定(bind)到我的 Controller 范围,如下所示:

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 并且没有更新。

这是一个 fiddle : http://jsfiddle.net/kannix/CGWbq/

最佳答案

Angular 应该 $watch safePostService.queue

尝试:

$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();

关于javascript - angularjs 将服务数组长度属性绑定(bind)到 Controller 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22066280/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com