3

I have a small issue. I have an object which I want to use to create two angular models without binding, based on initial object as prototype:

var def = {
   value: 'example'
}

in Angular:

var c = Object.create(def);
c.anothervalue = 12345;
$scope.c = c;

var d = Object.create(def);
d.anothervalue = 765432;
$scope.d = d;

c and d are created correctly, without binding. But I can't access initial value of the object in Angular View, even if in the controller it works good.

I read about and is something with Object.prototype but I couldn't find any solutions.

I've put a fiddle here

Alexandru R
  • 8,560
  • 16
  • 64
  • 98
  • You can actually access it by `c.value` or `d.value`. The problem is with the JSON filter. The JSON.stringify method doesn't take the inherited properties into account and that's why you don't see them in the output. – katranci May 08 '13 at 08:07

2 Answers2

3

Change your copy function from Object.create to angular.copy:

var c = angular.copy(def);

I tried it in your Fiddle, and I think it does what you want:

c:{ "value": "example", "anothervalue": 12345 } 
d:{ "value": "example", "anothervalue": 765432 }
Sparky
  • 8,437
  • 1
  • 29
  • 41
1

I found angular.copy() can be quite slow on larger objects.

Assuming that you have only simple variables and not any functions in your object, you can just use:

var c = JSON.parse(JSON.stringify(d));

Updated fiddle: http://jsfiddle.net/0d8fp9bz/

Source: https://stackoverflow.com/a/4591639/5385381

Warning: This can destroy Date objects, and anything that is not part of the JSON spec.

Community
  • 1
  • 1
ksav
  • 20,015
  • 6
  • 46
  • 66