Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 879
Banjo Drill Avatar asked Aug 10 '26 17:08

Banjo Drill


1 Answers

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);
like image 186
Muhammad Reda Avatar answered Aug 13 '26 05:08

Muhammad Reda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!