AngularJS读取JSON及XML文件的方法示例

本文实例讲述了AngularJS读取JSON及XML文件的方法。分享给大家供大家参考,具体如下:





 AJAX and promise
 
 


种类 价格 保质期
没有数据

种类 价格 保质期
没有数据

/*js*/
var app=angular.module("routingDemoApp",[]);
app.controller("AjaxJson",function($scope,$http){
 $scope.LoadJson=function(){
  $http.get("json.json")
   .success(function(data){
    $scope.products = data;
   })
   .error(function(){
    alert("出错")
   });
 };
});
app.controller("AjaxXml",function($scope,$http){
 $scope.LoadXml = function(){
  $http.get("xml.xml")
   .success(function(data){
    $scope.products = [];
    var productsElements = angular.element(data.trim()).find("product");
    for(var i=0;i 
 
/*json*/
[
 {"name":"apple","category":"fruit","price":"1.5","expiry":10},
 {"name":"banana","category":"fruit","price":"1.3","expiry":14},
 {"name":"pears","category":"fruit","price":"1.2","expiry":15},
 {"name":"tuna","category":"fish","price":"1.0","expiry":16}
]

 

/*xml*/

 
 
 
 

JSON:

1)配置对应的控制器,将scope和http服务注入该控制器中。

2)使用$http.get(),把将要读取的数据文件的url写入。

3)使用回调函数,成功时,将所得的data赋给$scope作用域下的变量products。

4)由前台使用no-repeat指令进行遍历逐一取出数据。

XML:

1)配置对应的控制器,将$scope和http服务注入该控制器中。

2)使用$http.get(),把将要读取的数据文件的url写入。

3)使用回调函数,在success里面进行成功读取XML数据时的操作。

4)定义一个$scope创建的作用域下的(也就会前台可以访问)数组变量products,后面会将读取到的数据逐一插入到里面。

5)定义一个数据变量productElements,将XML文件里面的 里的信息赋值给他。这里使用了trim()方法,原因是使用JS读取XML文件时前后会出现许多空字符。trim()方法可以将空字符去除。

6)使用for循环,将变量productElements里面每个 的内容都插入到之前定义好的数组变量products里面。

7)由前台使用no-repeat指令进行遍历逐一取出数据。

PS:这里再为大家提供几款关于xml与json操作的在线工具供大家参考使用:

在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson

在线格式化XML/在线压缩XML
http://tools.jb51.net/code/xmlformat

XML在线压缩/格式化工具:
http://tools.jb51.net/code/xml_format_compress

在线JSON代码检验、检验、美化、格式化工具:
http://tools.jb51.net/code/json

JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat

在线json压缩/转义工具:
http://tools.jb51.net/code/json_yasuo_trans

更多关于AngularJS相关内容感兴趣的读者可查看本站专题:《AngularJS指令操作技巧总结》、《AngularJS入门与进阶教程》及《AngularJS MVC架构总结》

希望本文所述对大家AngularJS程序设计有所帮助。

你可能感兴趣的:(AngularJS读取JSON及XML文件的方法示例)