Posted in Javascript onMay 17, 2017
本文实例讲述了angular.fromJson与toJson方法用法。分享给大家供大家参考,具体如下:
AngularJS的angular.fromJson()
方法可以把一个Json字符串中解析成一个对象,或对象数组:
<!DOCTYPE html> <html ng-app="App"> <head> <meta charset="UTF-8"> <title></title> <script src="../js/angular.js"></script> <script type="text/javascript"> angular.module("App", []) .controller("parseController", function($scope) { $scope.parse = function() { var json = '{"name":"liSi", "password":"321"}'; var jsonArr = '[{"name":"zhangSan", "password":"123"},{"name":"liSi", "password":"321"}]'; var obj = angular.fromJson(json); console.log(obj.name); var objArr = angular.fromJson(jsonArr); console.log(objArr[0].name); console.log(objArr[1].password); } }); </script> </head> <body> <div ng-controller="parseController"> <button ng-click="parse()">点击我!</button> </div> </body> </html>
控制台打印的结果如下:
liSi zhangSan 321
相应地,能够从Json到对象,就能够从对象到Json:
var obj = { name:"liSi", password:"321" } var str = angular.toJson(obj, true); console.log(str);
打印结果如下:
{ "name": "liSi", "password": "321" }
angular.fromJson与toJson方法用法示例
- Author -
itsonglin声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@