本文实例讲述了AngularJS读取JSON及XML文件的方法。分享给大家供大家参考,具体如下:
<!doctype html><meta charset="UTF-8"><html ng-app='routingDemoApp'><head> <title>AJAX and promise</title> <link href="bootstrap.min.css" rel="external nofollow" rel="stylesheet"> <link href="self.css" rel="external nofollow" rel="stylesheet"></head><body ><div class="panel panel-default" ng-controller="AjaxJson"> <!--创建控制器--> <div class="panel-body"> <table class="table table-striped table-hover"> <thead> <tr> <td>名</td> <td>种类</td> <td>价格</td> <td>保质期</td> </tr> </thead> <tbody> <tr ng-hide="products.length"> <td colspan="4" class="text-center">没有数据</td> <!--当没有数据的时候,显示这行,有数据的时候,隐藏。--> </tr> <tr ng-repeat="item in products"> <!--将数据放到item里面,逐一读取--> <td ng-bind="item.name"></td> <td ng-bind="item.category"></td> <td ng-bind="item.price"></td> <td ng-bind="item.expiry"></td> </tr> </tbody> </table> <p><button ng-click="LoadJson()">加载JSON数据</button></p><!--触发函数--> </div></div><div class="panel panel-default" ng-controller="AjaxXml"> <div class="panel-body"> <table class="table table-striped table-hover"> <thead> <tr> <td>名</td> <td>种类</td> <td>价格</td> <td>保质期</td> </tr> </thead> <tbody> <tr ng-hide="products.length"> <td colspan="4" class="text-center">没有数据</td> </tr> <tr ng-repeat="item in products"> <td ng-bind="item.name"></td> <td ng-bind="item.category"></td> <td ng-bind="item.price"></td> <td ng-bind="item.expiry"></td> </tr> </tbody> </table> <p><button ng-click="LoadXml()">加载xml数据</button></p> </div></div><script src="angular.min.js"></script><script src="angular-ui-router.js"></script><script src="ajax2.js"></script></body></html>
/*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<productsElements.length;i++){ var product = productsElements.eq(i); $scope.products.push({ name:product.attr("name"), category:product.attr("category"), price:product.attr("price"), expiry:product.attr("expiry") }); } }) .error(function(){ alert("错误"); }) };});
新闻热点
疑难解答
图片精选