YoroDiallo YoroDiallo - 1 year ago 47
AngularJS Question

How to add prototype property to existing object

I have few objects in array and I want to add some props from factory to object with type - date.

I don't need to remove old values from this object. I try to do it in this way:

angular.forEach($scope.things, function(item) {
if(item.type === 'date') {
item = DateFactory.prototype.createFactory();

but it doesn't work, where I'm wrong?
Plunker example

Answer Source

Changing the item within the forEach does not mutate the item. You need to use obj[key] instead:

angular.forEach($scope.things, function(item, key, obj) {
    if(item.type === 'date') {
      obj[key] = DateFactory.prototype.createFactory();

Updated plunker

Also, you should return the instance of your date object from the factory:

return new date();

..and then just call the method:

obj[key] = DateFactory.createFactory()