1

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}

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.