Javascript AngularJS工厂类,具有多个新实例';预计起飞时间

Javascript AngularJS工厂类,具有多个新实例';预计起飞时间,javascript,angularjs,oop,Javascript,Angularjs,Oop,首先-我对AngularJS很陌生 我已经创建了一个工厂类,我想创建一些实例,但问题是当一个工厂创建我的“Case”类的新实例时,我的其他实例将更改为。。我相信这很简单,但我想不出来 我认为我很聪明,创建了一个简单(通用)的类 我的工厂班级: .factory('Case', function($q, $http) { var optionsProto = { id : null, reference : "", fields : [] } var self

首先-我对AngularJS很陌生

我已经创建了一个工厂类,我想创建一些实例,但问题是当一个工厂创建我的“Case”类的新实例时,我的其他实例将更改为。。我相信这很简单,但我想不出来

我认为我很聪明,创建了一个简单(通用)的类

我的工厂班级:

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

})
控制台输出(类似)::


您引用了错误的
。尝试:

.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对象),请执行以下操作:


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

Haha。。完美-正是我需要的;)。。非常感谢。
.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;
    };
  }
});
  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;
    };
  }