How to change the value of the variable in Factory?

Asked

Viewed 85 times

3

Inside Factory has a variable countF 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();
    };
}

You can change the variable value countF that is outside the return at Factory? For example, increase it according to return of incrementCount?

  • Controller? No. Only if you move the countF into the object returned by Factory.

  • No, I just wish I could change the value of the variable in Factory. Because as far as I know the compiler only passes once in Factory and Functions every time they are called.

  • But where exactly? I guess I didn’t understand the question then.

  • Sorry for the lack of clarity. I want the var countF = 1 can switch to the same value as the Controller is sending. Example to var countF = 2.

  • Why don’t you create a method setCount in Factory?

  • How to do this?

Show 1 more comment

1 answer

2


I don’t know if I understand the question, but just as you have methods to get and increment this variable, you can create another one 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
    };
}
  • Really funfou. I had not thought of this possibility. Thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.