Banjo Drill
Banjo Drill

Reputation: 121

AngularJS reusable factory

I feel like this is probably a dumb question but I'm having trouble visualizing how to make this work.

I have a factory used to share data between controllers, like this:

app.factory('DataShare', function(){
    //Share Data between controllers via the sharedItem object and the get/set functions
    var sharedItem = {};
    function set(sharedData){
        sharedItem = sharedData;
    }
    function get(){
        return sharedItem;
    }
    return{
        set: set,
        get: get
    };
});

It works just fine. The issue is that are several times in my application where I need to share data. Currently, I have multiple factories with different names containing the same methods shown above. Can someone advise on the best way to create an abstract factory that I could reuse to share different data between different controllers?

Upvotes: 3

Views: 589

Answers (1)

Muhammad Reda
Muhammad Reda

Reputation: 27023

Create a new file and declare a new object.

var mySharedLib = mySharedLib || {}; // declare a new namespace for the shared code.

mySharedLib.DataShare = function() {
    // your factory logic
}

Then, the angular side:

app.factory('DataShare', mySharedLib.DataShare);

Upvotes: 3

Related Questions