Angular factory. how to create new factory instances?

I'm trying to create new factory instances, but all the time it prints the last instance (because of its singleton). How can I get a new instance every time I create using the keyword new

? I created an example of what I am trying to achieve at 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();
});

      

+3


source to share


1 answer


You are linking to it incorrectly. You have to refer to the called function instance with this

, and not the function name again.

Instead

var vm = CrudFactory;

      

change



var vm = this;

      

Working demo :

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

+2


source







All Articles