2013-08-11 6 views
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 

Что я делаю неправильно?

ответ

2

Это на самом деле мало связано с Угловым. Вы возвращаете объект (как говорит ошибка) из метода. Вы можете вернуть свою функцию 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; 
}); 

Btw. вы можете посмотреть это видео, как работает объектно-ориентированный JS: http://youtu.be/PMfcsYzj-9M

+0

Выдает мне новую ошибку 'TypeError: функция объекта (id, created, updated) { this._id = id; this._created = created; this._updated = обновлено; ' – Canttouchit

+0

Не может быть;): checkout this Plunkr http://plnkr.co/edit/ygi5OePQwSkLQt8Uthi1?p=preview – lpiepiora

+0

Да, вы правы, кажется, что проблема отображается {{x}}, во всяком случае это работает благодаря мужчине! – Canttouchit

Смежные вопросы