Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function inside factory method can communicate

Tags:

angularjs

i have one doubt regarding the factory directory of angular js.

suppose this is fact1 directory .I want to call funct1 method inside the funct2 method.

app.factory("fact1",function(){
  return{
     funct1:function(){
        //some code here
     },funct2:function(){
      //some code here
      // call here funct1()
     }
   }
 }); 

first tell me this is possible or not? if possible then how i can call funct1 method inside the funct2 method.

like image 339
Proxy_Server Avatar asked Jan 06 '14 19:01

Proxy_Server


3 Answers

Instead of directly returning in factory, you can do something like this:

app.factory("fact1",function(){
  var obj = {};

     obj.funct1 = function(){
        //some code here
     }

     obj.funct2 = function(){
      //some code here
      // call here funct1()
      obj.funct1();/* calling the funct1 */
     }
     return obj;

 }); 

This should work for you.

like image 103
Sandeep Gantait Avatar answered Nov 15 '22 12:11

Sandeep Gantait


Why not do something like this:

app.factory("fact1",function(){

    function funct1 () {
        // Do some code...
    }

    function funct2 () {
        // Do some code...
        funct1();
    }

    return{
        funct1: funct1,
        funct2: funct2
    };
}); 

I've personally found this way to be much more usable/readable than stashing every function in my return object. Also, I'm not a big fan of using this in my return objects.

like image 39
gonzofish Avatar answered Nov 15 '22 12:11

gonzofish


Sure it's possible. This is just normal javascript object usage:

return {
    funct1: function () {
        //some code here
    },
    funct2: function () {
        //some code here
        this.funct1();
    }
}

UPD. There was a little confusion in comments that it does not work. It does, however you need to understand that it's very important how funct2 method is called. Namely, method should not be detached from it's base object, otherwise this context will be different and this.funct1() will point to the wrong (usually inexistent) method. Common way to loose context:

$('.something').on('click', obj.funct2);

In the above, obj.funct2 this will be the HTML element object, not the obj anymore. However, below version will work properly:

// use anonymous function
$('.something').on('click', function() { obj.funct2() });

// bind explicitly to context
$('.something').on('click', obj.funct2.bind(obj));

Here is very important to understand MDN article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

like image 11
dfsq Avatar answered Nov 15 '22 13:11

dfsq