【问题标题】:AngularJS factory class with multiple instances new'ed具有多个实例的 AngularJS 工厂类 new'ed
【发布时间】:2015-03-07 00:14:08
【问题描述】:

首先 - 我对 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);

})

控制台输出(like)::

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

【问题讨论】:

    标签: javascript angularjs oop


    【解决方案1】:

    您引用了错误的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 语句总是返回创建的对象,并且它会中断函数的其余部分。

    【讨论】:

    • 哈哈 .. 完美 - 正是我所需要的 ;) .. 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多