4

I am putting the downloaded json object into an angular $scope, but I found that angular adds some framework dependent properties inside it.

I want to send the modified object back to server, is there a convenient way I can remove angular properties and get the plain object without angular scope properties like $$hashkey?

EDIT:

The possible duplicate question does not provide the answer I needed.

Calling angular.toJson gives me a plain string "$SCOPE", while calling angular.copy throws an error. I guess they are not designed to work with the $scope object itself?

Vicary
  • 1,026
  • 1
  • 15
  • 35
  • 1
    possible duplicate of [What is the $$hashKey added to my JSON.stringify result](http://stackoverflow.com/questions/18826320/what-is-the-hashkey-added-to-my-json-stringify-result) – Dalorzo Jul 17 '14 at 14:42
  • I've heard that Angular strips properties prefixed with $$ before sending them to the server. The [toJson() function](https://docs.angularjs.org/api/ng/function/angular.toJson) does this, and [$http seems to use it](https://github.com/angular/angular.js/blob/master/src/ng/http.js#L129). Though I'm a bit too lazy to verify it in a browser :) – Sunil D. Jul 17 '14 at 15:00
  • Sunil is correct, `angular.toJson(obj)` will do the trick. – runTarm Jul 17 '14 at 15:02
  • 1
    `angular.copy()` will also strip $$hashkey's – charlietfl Jul 17 '14 at 15:04
  • calling `angular.toJson` with $scope gives me the string `"$SCOPE"`, while `angular.copy` throws a an error `Error: [ng:cpws] Can't copy! Making copies of Window or Scope instances is not supported. http://errors.angularjs.org/1.2.20/ng/cpws` – Vicary Jul 17 '14 at 15:40

1 Answers1

0

You are right, the angular.toJson doesn't support the $scope object as you can see in the source code: Angular.js#L979

You could use the JSON.stringify() with a custom replacer function and copy a part of the logic in angular.toJson() like this;

JSON.stringify(obj, function(key, value) {
  if (typeof key === 'string' && (key.charAt(0) === '$' || key === 'this')) {
    // ignore any key start with '$',
    // and also ignore 'this' key to avoid a circular reference issue.
    return undefined;
  }

  return value;
});

Hope this helps.

runTarm
  • 11,537
  • 1
  • 37
  • 37
  • This kind of helps, I think they designed scopes in a way that this kind of usage is not recommended. I ended up wrapping the object into a scope property instead. – Vicary Oct 30 '15 at 07:18