0

我的代码:

webApp.controller ('entityCtrl', function ($scope, Entity) {  
    $scope.x = new Entity('1','3343','32434');
});


webApp.factory('Entity',function(){

  var _id,
      _created,
      _updated;


  //constructor

  function Entity(id,created,updated){


      this._id = id;
      this._created = created;
      this._updated = updated;

      return this;
  }

  var save = function (){
      console.log('save');
  };

  var update = function () {
      console.log('update');
  };

  var _delete = function () {
      console.log('delete');
};

  return {

      save: save,
      update: update,
      delete: _delete
  }

});

我得到的错误:

TypeError: object is not a function
at new <anonymous> (http://localhost/webApp/trunk/htdocs/js/rw/controllers.js:12:16)
at invoke (http://localhost/webApp/trunk/htdocs/js/vendors/angular.js:2902:28)
at Object.instantiate (http://localhost/webApp/trunk/htdocs/js/vendors/angular.js:2914:23)
at $get (http://localhost/webApp/trunk/htdocs/js/vendors/angular.js:4805:24)
at $get.i (http://localhost/webApp/trunk/htdocs/js/vendors/angular.js:4384:17)
at forEach (http://localhost/webApp/trunk/htdocs/js/vendors/angular.js:137:20)
at nodeLinkFn (http://localhost/webApp/trunk/htdocs/js/vendors/angular.js:4369:11)
at compositeLinkFn (http://localhost/webApp/trunk/htdocs/js/vendors/angular.js:4015:15)
at compositeLinkFn (http://localhost/webApp/trunk/htdocs/js/vendors/angular.js:4018:13)
at publicLinkFn (http://localhost/webApp/trunk/htdocs/js/vendors/angular.js:3920:30)    angular.js:5754

我究竟做错了什么?

4

1 回答 1

2

这实际上与 Angular 没什么关系。您正在从该方法返回一个对象(如错误所示)。您可能想要返回您的Entity函数。

考虑这个例子:

webApp.controller ('entityCtrl', function ($scope, Entity) {  
    $scope.x = new Entity('1','3343','32434');
});

webApp.factory('Entity',function(){
  var Entity = function(id,created,updated){
      this._id = id;
      this._created = created;
      this._updated = updated;
  };
  Entity.prototype.save = function (){
      console.log('save');
  };
  Entity.prototype.update = function () {
      console.log('update');
  };
  Entity.prototype._delete = function () {
      console.log('delete');
  };

  return Entity;
});

顺便提一句。您可能想观看此视频,了解面向对象 JS 的工作原理:http: //youtu.be/PMfcsYzj-9M

于 2013-08-11T20:54:21.697 回答