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

1
  • 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. Commented May 8, 2013 at 8:07

2 Answers 2

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 }
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.