angular.toJson/JSON.stringify values incorrect?

Problem

I have an object attached to a $scope that I want to serialize into JSON. The object has been setup with data binding so there are input fields using ng-model and what not. When attempting to call angular.toJson, the values aren't up to date.

The strange thing is that I figured my values weren't being updated like I thought. So I threw in some console.log calls for simplicity yet the values from console.log are correct yet they aren't for the JSON conversion? I tested it with JSON.stringify as well but the results were the same. Code:

// This looks fine
console.log('Data:', $scope.obj);
var temp = angular.toJson($scope.obj);
// This looks fine as well...
console.log('Data:', $scope.obj);
// Yet the JSON string isn't correct and contains old data?
console.log('Data:', temp);

Is this an Angular issue that I'm over looking that has to do with data binding? Or is something else going on?

Problem courtesy of: Josh Davis

Solution

Try calling var temp = angular.toJson($scope.obj); directly before working with temp variable for example by clicking the special button or doing like this:

var temp;
$scope.$watch('obj', function(newVal) {
    temp = angular.toJson(newVal);
    console.log('Data:', temp);
});

Please keep in mind that console.log() can print object not in that state when console.log() called. console.log() prints actual state only for string/number/boolean values. But if you called console.log($scope.obj) and after that $scope.obj is changed somewhere in the code (by loading the info via ajax, by event or by $scope.$apply()) you will see changed object in console (this works for DOM objects a well).

Solution courtesy of: Kichrum

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.