Search code examples
javascriptangularjsangular-servicesrevealing-module-pattern

Javascript Revealing Module Pattern in AngularJS Service not working


I'm using the following code in my angularJS service to get some task done :

angular.factory('promiseFactory', function(){
     var artistIds = [];

     function setArtistIds(artistIds){
       artistIds = artistIds;
     }

     return {
            createPromiseForNotification: promiseFactory,
            getNotis: getNotis,
            setNotis : setNotis,
            //setArtistIds : setArtistIds,
            artistIds : artistIds
        }
});

This factory is used in another factory notifications.js wherein I'm trying to set

promiseFactory.artistIds = [1,2,3];

on some ajax call but its not working, when I use the artistIds variable in any of the functions of my promiseFactory, it turns out to be blank array [] (the initial value). Why?

Ok, Secondly, this thing works when I use a function called setArtistIds to implement the same thing but even then I have to do something like

function setArtistIds(i){      // Right
     artistIds = i;
}

But not when I do it like this :

function setArtistIds(artistIds){      // Wrong
    artistIds = artistIds;
}

Can someone please explain me what wrong I'm doing.


Solution

    1. When you are executing this line of code:

      promiseFactory.artistIds = [1,2,3];

    You are only changing property of the object returned by your factory.

    But all your methods not even using it, they are using variable artistIds in the closure.

    In order to fix this error, add getter and setter to your factory.

    1. When you are naming parameter of the setter function the same way as your closure variable, you are hiding it. That's why it was not working.

    Just give it another name.

    angular.factory('promiseFactory', function(){
         var artistIds = [];
    
         function setArtistIds(newArtistIds){
           artistIds = newArtistIds;
         }
    
         function getArtistIds(){
           return artistIds;
         }
    
         return {
                createPromiseForNotification: promiseFactory,
                getNotis: getNotis,
                setNotis : setNotis,
                setArtistIds : setArtistIds,
                getArtistIds : getArtistIds,
            }
    });