Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning function from AngularJS factory

I'm trying to understand what the purpose is of the return part of this AngularJS factory method means?

return {
    getMessages: getMessages
  };

What happens if we added a new method to this factory called getAnotherMessage(), would we need to update this return segment?

myModule.factory('HelloWorld', function($q, $timeout) {

  var getMessages = function() {
    var deferred = $q.defer();

    $timeout(function() {
      deferred.resolve(['Hello', 'world!']);
    }, 2000);

    return deferred.promise;
  };

  return {
    getMessages: getMessages
  };

});
like image 234
catrapture Avatar asked Jan 19 '14 22:01

catrapture


2 Answers

You can also declare an empty object first and add functions into the object
and finally return the object.

 myModule.factory('HelloWorld', function($q, $timeout) {   
   var myobject = {};   
   myobject.getMessages = function() {    ...   };   
   myobject.getAnotherMessages = function() {    ...   };

   return myobject;   
 });
like image 38
hamster ham Avatar answered Oct 23 '22 01:10

hamster ham


factory is a provider constructor:

factory(fn) - registers a service factory function, fn, that will be wrapped in a service provider object, whose $get property will contain the given factory function.

Thus when the factory is first loaded by Angular it executes the function that's passed in and stores whatever is returned as the provider.

In other words, the following is run once, and only once- during bootstrapping:

var getMessages = function() {
   var deferred = $q.defer();

   $timeout(function() {
      deferred.resolve(['Hello', 'world!']);
   }, 2000);

   return deferred.promise;
 };

return {
   getMessages: getMessages
 };

The above gets a reference to the getMessage function and attaches it to the property getMessages inside the returned singleton object.

When the provider is then injected into your code, that returned object is what is passed in giving you access to the HelloWorld.getMessages function (and any other properties in the returned object).

So, yes, if you want to associate another property, such as a function, with the provider (that the factory constructs) you need to include it as a property of the returned singleton object:

return {
   getAnotherMessage: function() { ... },
   getMessages: getMessages
 };
like image 152
KayakDave Avatar answered Oct 23 '22 03:10

KayakDave