Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs bind service array length property to controller scope

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/

like image 541
kannix Avatar asked Dec 28 '25 20:12

kannix


1 Answers

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

like image 84
Paul Rad Avatar answered Dec 30 '25 09:12

Paul Rad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!