user1834664 user1834664 - 1 year ago 81
Javascript Question

How can AngularJS factory return an object

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();
return {

var add = function () {
var delete = function () {

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

How can i achieve this?

m59 m59
Answer Source

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();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download