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?
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?
Share Improve this question asked Nov 9, 2014 at 20:52 Josh DavisJosh Davis 6,8512 gold badges26 silver badges25 bronze badges 1- What do you mean values are not up to date? could you post more code? – Linial Commented Nov 9, 2014 at 21:11
1 Answer
Reset to default 5Try 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).