在 JSON.stringify-ing 和 JSON.parse-ing 之后恢复对象引用

Reinstate object reference after JSON.stringify-ing and JSON.parse-ing

本文关键字:JSON 恢复 对象引用 之后 stringify-ing parse-ing      更新时间:2023-09-26

考虑下面的一段代码。

我是我的 AngularJS 应用程序,当我用类别[0] 填充 $scope.records 的对象时,它们链接在一起,我可以在我的视图中显示类别属性:

.JS:

$scope.categories = [{
    title: 'Category 1'
}, {
    title: 'Category 2'
}];
$scope.records = [{title: 'New record', category: $scope.categories[0]}];

.HTML:

<select class="form-control input-sm" ng-model="record.category" ng-options="category.title for category in categories"></select>

但是:当我字符串化对象数组然后再次解析它时......

var json = JSON.stringify($scope.records);
var parsedJson = JSON.parse(json);
$scope.records = parsedJson;

。我"丢失了链接",我实际上是在创建一个副本,因此该类别不会显示为"已选择",因为:

$scope.records[0].category === $scope.categories[0]计算结果为 false。

有什么想法可以解决这个问题吗?

在这种情况下,可能是一个非常愚蠢的问题:对不起:-)

与其将完整的类别对象映射到记录中,不如将其映射为idname,如果您将其序列化为 json 并返回,它将始终有效

$scope.records = [{title: 'New record', category: $scope.categories[0].id}];

选择表达式变为

<select class="form-control input-sm" ng-model="record.category" ng-options="category.title for category.id in categories"></select>

尝试

$scope.$apply(function() {
   $scope.records = parsedJson;
});

简而言之,在您的示例中,angularjs 不知道某些内容已被更改,您必须通过调用$scope.$apply通知它。检查 http://docs.angularjs.org/api/ng.$rootScope.Scope

这个例子非常类似于我们试图将一个通过 angularjs 外部的 ajax 调用获取的变量分配给范围的情况,例如使用纯 jquery get 方法。在这种情况下,我们做了类似的事情(伪代码):

$.get("/api/something.json", function(results) {
  $scope.$apply(function() {
     $scope.records = results;
  });
});