angularJS简单调用接口,实现数组页面打印

相比较jquery ,angular对这种接口数据处理起来会方便的多。这里举例调用 中国天气网的api接口。

首先肯定要引入angular.js这个不多说

<link rel="stylesheet" href="css/bootstrap.css" type="text/css"></link>
<script type="text/javascript"  src="./js/angular.js"></script>

其次js代码如下:

    var app = angular.module("myApp", []);
    app.controller("myCtrl", ['$scope','$http', function($scope,$http) {
        var url='http://wthrcdn.etouch.cn/weather_mini?city='+'北京';
          $http.get(url).then(function (response) {
              $scope.cityname=response.data.data.city
              $scope.myweather= response.data.data.forecast;      
            });

    }]);

用ng-app管理angularjs 作用范围,控制器ng-controller这个去写你的方法。这些都是必须的
div代码:

<body  ng-app="myApp">
<div  ng-controller="myCtrl">  
<div>
        <p  style="font-size: 18px;text-align: center;font-weight: 600; color: rgb(200,10,10)">{{cityname}}</p>
         <table   class="table"  id="tale">
             <th>日期</th>
             <th>风力</th>
             <th>风向</th>
             <th>最高温度</th>
             <th>最低温度</th>
             <th>天气状况</th>
             <tr  ng-repeat="i  in  myweather ">
                 <td>{{i.date}}</td>
                 <td>{{i.fengli}}</td>
                 <td>{{i.fengxiang}}</td>
                 <td>{{i.high}}</td>
                 <td>{{i.low}}</td>
                 <td>{{i.type}}</td>
             </tr>
         </table>
</div>
</body>

这里非常方便的是这个 :ng-repeat,循环打印出你想打印的数据。当然你们以后肯定会遇到类似这种:

这是因为你的数组中存在相同数据,所以你只需要在 ng-repeat中加入"track by $index"就好了, 例如ng-repeat=" i in  你的数据   track by $index" 。

页面展示如下:

 本文属作者原创,如有转载请标明文章出处:http://www.cnblogs.com/mobeisanghai/p/7459020.html
作者:漠北桑海

原文地址:https://www.cnblogs.com/mobeisanghai/p/7459020.html