Jon
Jon

Reputation: 1727

set/get in a Factory

How can I use a set/get in a Factory. I need to set a value (scope) to the factory so I can $compile. But I can't seem to get the syntax correct or get it working. What wrong with the following? How can I set the value of PrivateVar to $scope.

I want to call

format.setVar($scope) - in my controller.

My factory looks like this..

pqpApp.factory('format', function ($compile, config) {

    var PrivateVar = {};

    var getVar = function () {
        return PrivateVar
    }

    var setVar = function(value)
    {
        PrivateVar = value;
    }

    return {
        getVar: getVar,
        setVar: setVar
    }


  var formatter = {}

(functions go here)

return formatter;

Upvotes: 0

Views: 1312

Answers (2)

chris
chris

Reputation: 1817

If we take your code as is, then you are trying to return two objects from the same factory (the object on line 14 and the formatter on the last line).

In order to get back the setVar and getVar functions from the factory while keeping PrivateVar private, you can write the factory like this:

    pqpApp.factory('format', function ($compile, config) {

        var PrivateVar = {};

        this.getVar = function () {
            return PrivateVar;
        }

        this.setVar = function(value)
        {
            PrivateVar = value;
        }

        return {
            getVar: this.getVar,
            setVar: this.setVar 
        }
        // or could just 'return this;'
}

Then you can set PrivateVar to whatever you like from the controller i.e.

pqpApp.controller('testCtrl', function($scope, format) {
    format.setVar($scope);
})

Upvotes: 1

pgrodrigues
pgrodrigues

Reputation: 2078

Not sure if I understood your question but here you go...

Maybe you are confusing three different concepts: service/factory/provider.

A simple factory can be done like this:

myApp.factory('MyFactory', function () {
        var myFactory = {};

        // myProperty
        myFactory.myProperty = 'Hello';

        // Set myProperty
        myFactory.setProperty = function (value) {
            this.myProperty = value;
        };

        return myFactory;
    });

Then just inject the factory MyFactory in your controller and use:

MyFactory.setProperty('World');    // Sets myProperty with value 'World'
$scope.property = MyFactory.myProperty;    // Access myProperty value and save it to `$scope.property`

Upvotes: 2

Related Questions