Search code examples
javascriptangularjsangularjs-serviceinitialization

How to initialize a service by calling a function from the service itself


I wrote a service. with a function inside it. Is it possible to initialize the service with that function? Have a look at this code.

app.factory('SidebarService',function(){
  var self = this;
  self.init();
  return{
    init : function(){
      alert("This is sidebar");
    }
  };

});

I tried to call the init by self.init();. But it is not working.

Pluker Link : http://plnkr.co/edit/gYw2VlneeUIJ7kHJF0Xz?p=preview


Solution

  • app.factory('SidebarService',function(){
        var obj = {};
        obj.init = function(){
            alert("This is sidebar");
        }  
        obj.init();
        return obj;  
    });
    

    Plunk