Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular.toJson/JSON.stringify values incorrect?

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?

like image 268
Josh Davis Avatar asked Mar 26 '26 08:03

Josh Davis


1 Answers

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).

like image 98
Kichrum Avatar answered Mar 28 '26 03:03

Kichrum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!