Access nested function closures in angular factory

2.3k views Asked by At

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

There are 2 answers

3
Debasish Mohapatra On BEST ANSWER

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();
    }
}());
0
Freezystem On

Just try :

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

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