AngularJS 工厂 class 有多个新实例

AngularJS factory class with multiple instances new'ed

首先 - 我是 AngularJS 的新手 ...

我创建了一个工厂 class,我想为其创建一些实例,但问题是当创建我的 "Case" class 的新实例时,我的其他实例更改为..我确定它很简单,但无法弄清楚。

我觉得我做一个简单的(通用的)很聪明class

我的工厂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;
    };
  }
})

我的控制器:

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

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

  console.log($scope.cases);

})

控制台输出(如)::

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

您引用的是错误的 this。尝试:

.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;
    };
  }
});

如果要保留 self 变量(以便所有函数都绑定到 Case 对象),请执行:

  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;
    };
  }

另外:请注意,我删除了 return self; 行。这是因为 new 语句总是 return 创建的对象,它会中断函数的其余部分。