Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick Way to "Un-Angularize" a JS Object

Angular adds expando properties, "hashes," etc., to my deep object structure when two-way binding is in use. That's fine, but I'm interested in retrieving a JSON snapshot of my object tree with only the things that originally belonged there. Does Angular provide a way to get a "vanilla" version of a bound object?

(I wouldn't want to merely store the "original value" before binding kicks in, since I would want to reflect any changes made via the UI.)

like image 224
blaster Avatar asked May 14 '13 15:05

blaster


1 Answers

short answer:

There's a nice built in function:

angular.toJson(yourObj);

longer explanation:

The only difference between angular.toJson and JSON.stringify is that it runs it through a filter which strips out the hashes/ids and turns window, document, and scope into strings. If you want to roll your own function to do this: here is relevant snippet from Angular.JS source code:

if(/^\$+/.test(key)) {
    val = undefined;
} else if (isWindow(value)) {
    val = '$WINDOW';
} else if (value &&  document === value) {
    val = '$DOCUMENT';
} else if (isScope(value)) {
    val = '$SCOPE';
}

note: the isWindow and isScope functions are not exported, so you'd need a little more hacking to get that function to work exactly the same way.

source: http://docs.angularjs.org/api/angular.toJson and https://github.com/angular/angular.js/blob/master/src/Angular.js

There's also a angular.fromJSon function which is essentially JSON.parse.

Update It's worth noting that the $http service does this automatically for you when you specify a model as the data for an $http request.

like image 196
Jonathan Rowny Avatar answered Oct 14 '22 00:10

Jonathan Rowny