繁体   English   中英

angularjs将服务数组长度属性绑定到控制器范围

[英]angularjs bind service array length property to controller scope

我正在尝试将数组长度从其他服务绑定到我的控制器范围,如下所示:

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/

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM