3

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();
});
Alex Koretzki
  • 155
  • 2
  • 11
  • Change vm from CrudFactory to this – Vivz Aug 03 '17 at 11:34
  • Possible duplicate of [Non-Singleton Services in Angular](https://stackoverflow.com/questions/16626075/non-singleton-services-in-angular) – Mistalis Aug 03 '17 at 11:59
  • vm is supposed to be used in controllers; does not make any sense to me to use it in factories (we bind view/tpl and model in controllers). – Ramsing Nadeem Aug 03 '17 at 12:02

1 Answers1

2

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/

Vivz
  • 6,625
  • 2
  • 17
  • 33
  • how its possible to create new instance if the factory is singleton? – Alex Koretzki Aug 03 '17 at 12:10
  • You can check this link for more details https://stackoverflow.com/questions/16626075/non-singleton-services-in-angular ? Check the fiddle to see how we can use objects to trigger the functions in factory – Vivz Aug 03 '17 at 12:21