Arsen Babajanyan Arsen Babajanyan - 1 month ago 19
AngularJS Question

Update scope value inside service

I have the following controllers in my app:

Main controller:

app.controller('AppCtrl', ['$scope', function ($scope) {
$scope.app = {
amount: 0
};
}]);


Child Controller:

app.controller('ChildCtrl', ['$scope', function ($scope) {
var timeLoop = function (amount) {
$timeout(function () {
$scope.app.amount++;

if($scope.app.amount < amount) {
timeLoop(amount);
}
}, 10);
}
timeLoop(20);
}]);


Another Child Controller:

app.controller('AnotherChildCtrl', ['$scope', function ($scope) {
var timeLoop = function (amount) {
$timeout(function () {
$scope.app.amount++;

if($scope.app.amount < amount) {
timeLoop(amount);
}
}, 10);
}
timeLoop(100);
}]);


How to do the same thing with the service? I don't want use timeLoop function inside MainCtrl. Do you know how I can do this?

Answer

Your Main Controller:

app.controller('AppCtrl', ['$scope','timeOutService', function ($scope,timeOutService) {
    $scope.app = {
        amount: timeOutService.amount 
    };
}]);

You could have a generic service like this:

app.service('timeOutService', function($timeout) {
    this.amount = 0;
    this.timeLoop = function (amount) {
        var that = this;
        $timeout(function () {
            that.amount++;

            if(that.amount < amount) {
                that.timeLoop(amount);
            }
        }, 10);
    }
});

And in your multiple controllers, you can inject the same:

Child Controller:

app.controller('ChildCtrl', ['$scope','timeOutService', function ($scope,timeOutService) {     console.log("timeOutService", timeOutService);
    timeOutService.timeLoop(20);
}]);

Another Child Controller:

app.controller('AnotherChildCtrl', ['$scope','timeOutService', function ($scope,timeOutService) { 
    timeOutService.timeLoop(20);
}]);

Below is a working fiddle: https://jsfiddle.net/40zodv7b/