pkdkk
pkdkk

Reputation: 3961

AngularJS factory class with multiple instances new'ed

first - i'm pretty new to AngularJS ...

I have made a factory class, that I want to make some instances of, but the thing is that when a make a new instance of my "Case" class, my other instances changes to.. I'm sure it's pretty simple, but can't figure it out.

I think I was smart to make a simple (generic) class

my factory class:

.factory('Case', function($q, $http) {
  var optionsProto = {
    id : null,
    reference : "",
    fields : []
  }

  var self = this;

  return function Case(options) {
    angular.extend(self, optionsProto, options);
    return self;

    // Updates via. webservice, if posible
    this.update = function get(options) {
      // not implemented yet
      return self;
    };

    // Saves via. webservice, if posible
    this.save = function save() {
      // not implemented yet
      return self;
    };
  }
})

my controller:

.controller('CasesCtrl', function($scope, Case) {

  $scope.cases = [
    new Case({"id": 1}),
    new Case({"id": 2}),
    new Case({"id": 3}),
  ];

  console.log($scope.cases);

})

console output (like)::

Object {id: 3}
Object {id: 3}
Object {id: 3}

Upvotes: 1

Views: 663

Answers (1)

tcooc
tcooc

Reputation: 21229

You are referencing the wrong this. Try:

.factory('Case', function($q, $http) {
  var optionsProto = {
    id : null,
    reference : "",
    fields : []
  }; 

  return function Case(options) {
    angular.extend(this, optionsProto, options);

    // Updates via. webservice, if posible
    this.update = function get(options) {
      // not implemented yet
      return this;
    };

    // Saves via. webservice, if posible
    this.save = function save() {
      // not implemented yet
      return this;
    };
  }
});

If you want to preserve the self variable (so that all functions are bound to the Case object), do:

  return function Case(options) {
    var self = this;
    angular.extend(self, optionsProto, options);

    // Updates via. webservice, if posible
    this.update = function get(options) {
      // not implemented yet
      return self;
    };

    // Saves via. webservice, if posible
    this.save = function save() {
      // not implemented yet
      return self;
    };
  }

Also: Note that I removed the return self; line. This is because new statements always return the created object, and it was interrupting the rest of the function.

Upvotes: 3

Related Questions