繁体   English   中英

JSON字符串中的AngularJS对象

[英]AngularJS Object from JSON String

我有一个看起来像这样的Angular对象(menuItems包含更多数据,但那不是重点):

$scope.data = {
   title:'Title',
   place:'Somewhere'
   menuItems: [{
        title: "This is a Title",
        name: "John"},
                {
        title: "Another Title",
        name: "Frank"} ]
};

我使用默认值创建此$ scope.data。 他们总是一样的。 此数据用于使用ng-model填充html页面。 以及显示所有菜单项的ng-repeat调用。

<input class="text form-control" ng-model="data.title"></div>
<div ng-repeat="item in data.menuItems">
   <input class="text form-control" ng-model="item.name"></div>
   ...
</div>

然后,我成功将数据对象导出为JSON字符串,如下所示:

$scope.json = angular.toJson($scope.data, false);

产生类似于此的JSON字符串:

{"menuItems":[{"title":"This is a title","name":"John"},{"title":"Another Title","name":"Frank"}],"title":"Title", "place":"Somewhere"}

我现在想做的是加载此JSON字符串并覆盖$ scope.data对象(以提供修改现有JSON字符串的方法)。

我像这样加载字符串:

var json = JSON.stringify("{"menuItems":[{"title":"This is a title","name":"John"},{"title":"Another Title","name":"Frank"}],"title":"Title", "place":"Somewhere"}");
$scope.data = JSON.parse(json);

但是不会更新任何数据,并且在ng-repeat中创建的所有div都会消失。

我无法更改JSON的结构,因为在其他应用程序中以这种方式使用了它。 有没有办法实现我想要的?

谢谢。

由于您正在使用$scope.json = angular.toJson($scope.data, false); 在angular中进行相反操作的方法是angular.fromJson($scope.json)

另外,请确保您的JSON有效。 "{"menuItems":[{"title":"This is a title","name":"John"},{"title":"Another Title","name":"Frank"}],"title":"Title", "place":"Somewhere"}")看起来您的内引号没有被转义,或者您没有使用单引号作为外引号。

您必须转义引号:

var json = JSON.parse("{\"menuItems\":[{\"title\":\"This is a title\",\"name\":\"John\"},{\"title\":\"Another Title\",\"name\":\"Frank\"}],\"title\":\"Title\", \"place\":\"Somewhere\"}");

你也在串弦! JSON.stringify期望对象并返回JSON字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM