3

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/

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

thank you so much! it works :) What do you mean with this comment: You decrease the queue array in case of success ?
Just to explain why the count increase before decreasing, not very important :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.