0

I am trying to access a nested function inside a factory which I injected to a controller in AngularJS, but just get a 'function is undefined' error. I think the controller cannot even access to the inner function. Why? Is this even legit JavaScript?

The service

(function () {
    'use strict';

    angular
        .module('myModule', [])
        .factory('myFactory', myFactory);

    function myFactory() {
        var outerVar = 0;

        function foobar() {
            var innerVar;

            function foo() {
                innerVar = outerVar++;
                console.log(innerVar);
            }

            function bar() {
                innerVar = outerVar--;
                console.log(innerVar);
            }

            return {
                foo: foo,
                bar: bar
            }
        }

        return {
            foobar: foobar
        }
    }
}());

The controller

(function () {
    'use strict';

    angular
        .module('myModule')
        .controller('myController', myController);

    function myController(myFactory) {

        myFactory.foobar.foo();
    }
}());
uloco
  • 2,283
  • 4
  • 22
  • 37

2 Answers2

1

Just try :

myFactory.foobar().foo();
myFactory.foobar().bar();

It's the way it's intended to be used.

Freezystem
  • 4,494
  • 1
  • 32
  • 35
1

You have to call the foobar function, then it will return the desired object

(function () {
'use strict';

angular
    .module('myModule')
    .controller('myController', myController);

    function myController(myFactory) {

        myFactory.foobar().foo();
    }
}());
  • Would it be better to use a `service` here instead of a `factory`? Perhaps it would be more elegant... – uloco Jun 12 '15 at 12:58
  • 1
    see, the difference between using a service and a factory is that if you use a factory , and when you inject that factory, angular will call the factory function and return to you the result i.e **foobar** object in this case. However , if you use a service and you inject it some where you will be provided with a new instance of the function i.e **new myFactory()**. – Debasish Mohapatra Jun 12 '15 at 13:06
  • this link will be very helpful for you to decide which design pattern you should follow http://stackoverflow.com/questions/15666048/service-vs-provider-vs-factory – Debasish Mohapatra Jun 12 '15 at 13:09