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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With