<!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"); // factory 简版的 provider // app.factory("getWeatherFromData", function () { // return { // run: 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; // } // }; // }); // 单例 // app.service("getWeatherFromData", function() { // this.run = 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; // } // }); app.provider("getWeatherFromData", function () { this.$get = function () { return 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; } } }); app.controller("myCtrl", function ($scope, $http, URL, getWeatherFromData) { $http.get(URL).then(function (response) { var weather = getWeatherFromData(response); $scope.weather = weather; }, function (response) { console.log(response.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>
angularjs请求数据解析并渲染到表格中(天气预报)
最新推荐文章于 2024-04-18 16:27:41 发布