How to change the value of the variable in Factory?

3

Inside Factory has a variable countF with value 1:

Factory

app.factory('testFactory', function(){
    var countF = 1;
    return {
        getCount : function () {

            return countF;
        },
        incrementCount:function(){
           countF++;
            return countF;
        }
    }               
});

Controller

function FactoryCtrl($scope, testService, testFactory)
{
    $scope.countFactory = testFactory.getCount;
    $scope.clickF = function () {
        $scope.countF = testFactory.incrementCount();
    };
}

Is it possible to change the value of the countF variable that is outside the return in Factory? For example, increase it by% w / w% w / w%?

    
asked by anonymous 20.10.2015 / 18:51

1 answer

2

I do not know if I understand the question, but just as you have methods to get and increment this variable, you can create another to define its value (a setter ):

app.factory('testFactory', function(){
    var countF = 1;
    return {
        setCount : function (val) {
            countF = val;
        },
        getCount : function () {
            return countF;
        },
        incrementCount:function(){
            countF++;
            return countF;
        }
    }               
});
function FactoryCtrl($scope, testService, testFactory)
{
    testFactory.setCount(10);  // seta como 10
    $scope.countFactory = testFactory.getCount; // pega o valor 10
    $scope.clickF = function () {
        $scope.countF = testFactory.incrementCount(); // incrementa a partir de 10
    };
}
    
20.10.2015 / 19:39