本文實例講述了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("錯誤"); }) };});
新聞熱點
疑難解答
圖片精選