最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - angular.toJsonJSON.stringify values incorrect? - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 5

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

发布评论

评论列表(0)

  1. 暂无评论