angular-网络请求天气

来源:互联网 发布:天刀男号捏脸数据 编辑:程序博客网 时间:2024/05/22 02:17
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script type="text/javascript" src="angular-1.3.0.js"></script>
    <title></title>
    <script type="text/javascript">
        var app = angular.module("myApp", []);


        app.value("URL", "https://free-api.heweather.com/v5/weather?city=beijing&key=545d63e185fc48169a43cbabba6e74d2");


        app.factory("weather", function ($http, $q, URL) {
            return function () {
                return $http.get(URL).then(function (response) {
                    var data = response.data.HeWeather5[0];


                    var weather = {city: data.basic.city, txt: data.now.cond.txt, day3: [], hour4: []};


                    for (var i in data.daily_forecast) {
                        weather.day3.push({
                            date: data.daily_forecast[i].date,
                            txt: data.daily_forecast[i].cond.txt_d
                        });
                    }


                    for (var i in data.hourly_forecast) {
                        weather.hour4.push({
                            time: data.hourly_forecast[i].date,
                            txt: data.hourly_forecast[i].cond.txt
                        });
                    }


                    return weather;
                }, function (response) {
                    return $q.reject(response.status);
                });
            }
        });


        app.controller("myCtrl", function ($scope, weather) {
            weather().then(function (weather) {
                $scope.weather = weather;
            }, function (status) {
                console.log(status);
            });
        });
    </script>
</head>
<body ng-app="myApp">
<div ng-controller="myCtrl">
    <div>
        城市:<i>{{ weather.city }}</i>
    </div>
    <div>
        天气:<i>{{ weather.txt }}</i>
    </div>
    <div>未来3天天气:</div>
    <table border="1">
        <tr>
            <th>日期</th>
            <th>天气</th>
        </tr>
        <tbody ng-repeat="value in weather.day3">
        <tr>
            <td>{{ value.date }}</td>
            <td>{{ value.txt }}</td>
        </tr>
        </tbody>
    </table>
    <div>未来几小时天气:</div>
    <table border="1">
        <tr>
            <th>时间</th>
            <th>天气</th>
        </tr>
        <tbody ng-repeat="value in weather.hour4">
        <tr>
            <td>{{ value.time }}</td>
            <td>{{ value.txt }}</td>
        </tr>
        </tbody>
    </table>
</div>
</body>
</html>
原创粉丝点击