Search code examples
javascriptangularjsangular-factory

angular factory. how to create new instances of the factory?


I am trying to create new instances of a factory but, all the time it prints the last instance (because of its singleton). How can I achieve new instance every time I create with the new keyword? I created example of what I am trying to achieve in jsfiddle.net Thanks.

angular.module('mainModule', []);

  Crud.$inject = ['$http'];

    function Crud($http) {

        function CrudFactory(crudDTO) {
            var vm = CrudFactory;
                        vm.x = 1;
            vm.addX = addX;
            vm.getX = getX;
            vm.print = print;

            function addX(){
                vm.x +=1;
            }
            function getX(){

                return vm.x;
            }
            function print(){
                console.log(crudDTO.entity);
            }

            return vm;
        }

        return CrudFactory;
    }

    angular
        .module('mainModule')
        .factory('Crud', Crud);


    angular.module('mainModule').controller('mainCtrl', function($scope,Crud){
    var a = new Crud({entity:"test1"});
    var b = new Crud({entity:"test2"});
    //a.addX();
    //$scope.a =b.getX();
    a.print();
    b.print();
    a.print();
});

Solution

  • You are referencing it wrongly. You have to reference the instance of the called function with this rather than with the function name again.

    Instead

    var vm = CrudFactory;
    

    change

    var vm = this;
    

    Working Demo:

    http://jsfiddle.net/haqL7m5q/2/