7

I have a requirement in which i should write factory. This factory should contain 3 function init, save and delete

I should call init function from controller. This function returns an object. This object has the function to execute the add and delete function.

how can i achieve this?

Following is my code, It execute the init function successfully but when i try to use the object which was returned in add or delete, it says object is empty

angularApp.factory('SomeFactory', function(){
var client = new Client(); // this client is defined in another javascript file
                           // this is the object which we should return
var clientReady = function () {
     var cv = client.GetVersion();
     showIDs();
};
return {
    initClient:function(requiredUID){
        client.setAttribute("clientReadyCallback",clientReady);
    }//,

};
 var add = function () {
     client.someapi;
 };
var delete = function () {
     client.someapi;
 };`
});

in controller i call the below calls
SomeFactory.initClient("username");
SomeFactory.add();// throws error

How can i achieve this?

4
  • You are never reaching the var add = function() ... because you are returning before it. Commented Nov 21, 2013 at 16:58
  • even if i ass those function inside return with comma separated, it still doesn't work Commented Nov 21, 2013 at 17:01
  • Could you put your code in a fiddle? Commented Nov 21, 2013 at 17:03
  • the code which i have posted is stripped code. The actual code is very restrictive by company policy. So even if i post this in fiddle it may not work. Commented Nov 21, 2013 at 17:05

3 Answers 3

19

First of all, you aren't returning a factory, but a service. It's a factory that creates a service, so adjust your naming convention like so: app.factory('someService'

Your code is a mess and has errors, so I'll just show you the basics of returning a service object.

app.factory('someService', function() {
  var someService = {  //build this object however you want
    add: function() {

    },
    save: function() {

    }
  };

  return someService; //return the object
}); //end factory

in your controller: someService.add();

Sign up to request clarification or add additional context in comments.

5 Comments

Actually this answer is a little off. Returning an object is in fact a factory, not a service. Returning an object allows the factory to produce a new instance, i.e. it can be new'd, giving you the ability to produce multiple copies of the service from a single injection source. See this article for details: blog.manishchhabra.com/2013/09/… or my answer in this question
You're not saying anything different than what I said. You're just adding an additional detail about creating a new instance with new. The way I think about it, that's not related to angular. You can operate on the injected value of the service however you want to. As to your answer, var instanceOne = new $factory; is not accurate naming. A factory is a function that creates something. $factory in your example is what was created by the factory, a service.
@NickSteele See Angular's own wording in the docs docs.angularjs.org/guide/services
I agree with everything you're saying. I probably should have said I'm adding additional detail instead of "the answer is a little off", looking back, I can see how that might be offensive or imply you made a mistake. I'm sorry about that and will use this interaction to improve my behavior. You are right about my inaccurate naming. I just wanted to point out the importance of a singleton vs a factory method, most people don't know what's happening, or that there is a difference, and get confused when they need one or the other and go off looking to reinvent the wheel.
Ah. I understand now what you meant now. Cool. It is a helpful detail.
3

A factory and service are actually different in one simple but very, very important way.

A Factory returns services that can be new'd.

In other words, you can do this:

var instanceOne = new $factory;
var instanceTwo = new $factory;

...and then call them as separate entities. This is in fact what the factory pattern is all about.

Here is a simple example of a factory that you can get copies of...

app.factory('myFactory', function() {
    return {
        talk: function(what) {
            return "Say " + what;
        }
    }
});

If instead you want a Service, you need to reference methods inside it by this.methodName, then you're just returning the service itself, or, a singleton pattern. Like so...

app.service('myService', function() {
    this.talk = function(what) {
        return "Say " + what;
    };
});

As a side note; if you look at my code, Angular now supports actually defining services via the service keyword, or, the factory keyword. In the source, you can see that they both literally reference the same code.

That's how similar they are, and in fact these two factory and service methods are interchangeable, so, if you got confused at first, don't sweat it; there is almost no difference at all... almost :)

... lots of people seem to want to know: "How can you return a factory or service that just has one function, i.e., it, itself, is the function?" Easy.. like this...

app.factory('myFactory', function() {
    return function(what) {
            return "Say " + what;
    }
});

Comments

2

this is an Authentification factory from a real project

//factory using firebase Athentication service
myApp.factory('Authentication', function($firebase,$firebaseAuth,$location){

	var ref = new Firebase("URL_to_firebase");
    var simpleLogin = $firebaseAuth(ref);

    var myObject = {
    	//user is the data from the FORM
    	login : function(user){
    		return simpleLogin.$authWithPassword({
			  email: user.email,
			  password: user.password
			});
    	}//login
    }//password

    return myObject;//factory should return something

});

//and then you call like this in your controller
myApp.controller('myController' , function($scope, $location, $firebaseAuth,Authentication){
	
	$scope.login = function() {
		Authentication.login($scope.user)
	} //login

	
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.