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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With