How to convert string to object in Angularjs [duplicate]

て烟熏妆下的殇ゞ 提交于 2019-12-10 01:42:14

问题


I have a string like :

$scope.text = '"{\"firstName\":\"John\",\"age\":454 }"';

and I want to convert to js object:

 $scope.tmp =  {"firstName":"John","age":454 };

Note: JSON.parse() doesn't work!!

It's my sample in codepen


回答1:


You can do it with angular.fromJson()

in your sample, it would have been $scope.tmp = angular.fromJson($scope.text);

The difference between JSON.Parse() and angular.fromJson, is that angular will check to make sure a string is provided. If it is already an object, it will return the same object.



来源:https://stackoverflow.com/questions/38180525/how-to-convert-string-to-object-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!