Hitu Bansal
Hitu Bansal

Reputation: 3137

AngularJS : How to call a function within factory?

I have two function in factory

here is some code

.factory('getArticles', function ($http, $q) {
   return {
       abc : function() {
        var deferred = $q.defer();
        // my code 
            res= this. bcd();
            console.log(res); // undefined
          deferred.resolve(res);

          return deferred.promise;
       },
       bcd: function() {

        //some codee 

         return res; 

       }
   }

});

Now from controller i am calling abc function but when i checked value of res under logs. this is showing undefined.

Any idea ? how to do this ?

Thanks

Upvotes: 1

Views: 3014

Answers (3)

wiherek
wiherek

Reputation: 1923

@Vineet's answer was correct for services, which are instantiated, but factories should just return an object.

I like @peek4y's answer, but it can be further improved, to still have abc() private:

(function () {
'use strict';

var getArticles = function ($http, $q) {

  function bcd() {
    var res;
    // some logic
    return res;
  }

  function abc() {
    var deferred = $q.defer();
    var res = bcd();
    console.log(res); 
    deferred.resolve(res);
    return deferred.promise;
  }

  //return only the functions you want to expose

  return {
    abc: function () {
      return abc();
    }
  }
});

angular.module('myApp')
  .factory('getArticles', getArticles);

}());

Upvotes: 3

peek4y
peek4y

Reputation: 31

Always, separate the concerns.

.factory('getArticles', function ($http, $q) {

  function abc() {
    var deferred = $q.defer();
    res= bcd();
    console.log(res); 
    deferred.resolve(res);
    return deferred.promise;
  }

  function bcd() {
    //some logic
    //Make sure your logic is returning proper value.
    return res;
  }


  //return only those functions you want to expose
  return {
    abc: abc
  }
});

in the return statement, you can basically expose only those methods, which you would consume.

Upvotes: 1

Vineet
Vineet

Reputation: 4635

Yes exactly as Mr. luschn has said but you can call your factory/service function from the controller by changing as below defined. You should define your function with this reference in factory

.factory('getArticles', function ($http, $q) {

       this.abc = function() {
        var deferred = $q.defer();
        // my code 
            res= this. bcd();
            console.log(res); // undefined
          deferred.resolve(res);

          return deferred.promise;
       }

       this.bcd = function() {

        //some codee 

         return res; 

       }

});

in your controller you can call by

getArticles.abc()

If you need to call a factory's function from another factory function call simply

this.bcd();

Upvotes: 0

Related Questions