angularjs實現查詢天氣的小案例(跨域請求)

效果圖:



貼代碼:
<!DOCTYPE html>
<html lang="en" ng-app="App">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
      
        .box {
        	position: relative;
        	width: 600px;
        	height: 400px;
        	margin: 0 auto;
        }
        .chaxun {
        	background-color: rgba(255,255,255,0.1);
        	position: absolute;
        	top:30px;
        	left: 50px;
        	/*float: left;*/
        }
        .bgimg {
        	width: 600px;
        }
	</style>

</head>
<body ng-app="App">
	
	<div ng-controller="WeatherController" class="box" >
	<img src="images/n-bg1.jpg" class="bgimg">
	<div class="chaxun">
		 <input type="text" ng-model="text">
	    <button ng-click="cha()">查詢當前位置天氣</button>
		<table>
			<!-- 視圖 -->
			<p>當前時間是:{{time|date:'yyyy-MM-dd hh:mm:ss'}}</p>
			<tr ng-repeat="item in weatherData">
			   <!-- <p>你的位置:{{currentCity}}</p> -->
				<td>{{item.date}}</td>
				<td><img ng-src="{{item.dayPictureUrl}}" alt=""></td>
				<td><img ng-src="{{item.nightPictureUrl}}" alt=""></td>
				<td>{{item.temperature}}</td>
				<td>{{item.weather}}</td>
				<td>{{item.wind}}</td>
			</tr>
		</table>
	</div>
	  </div> 
	<script src="js/angular.min.js"></script>
	<script>
		var App = angular.module('App', []);
		// 定義控制器並聲明依賴
		App.controller('WeatherController', ['$scope', '$http', '$interval', function($scope, $http, $interval) {
			// 頁面顯示當前時間
			$interval(function(){
				$scope.time = new Date();
			},1000);
			// 查詢各個城市的天氣
			$scope.text = '吉林';//初始化輸入框的參數
			$scope.cha = function(){
				$http({
				method: 'jsonp', // 支持jsonp,
				url: 'http://api.map.baidu.com/telematics/v3/weather?callback=JSON_CALLBACK',
				params: { // 請求的參數
					location: $scope.text,
					output: 'json',
					ak: '0A5bc3c4fb543c8f9bc54b77bc155724'
				}
			}).success(function (data) {
				// 請求回的數據放到模型上
				$scope.currentCity = data.results[0].currentCity;
				$scope.weatherData = data.results[0].weather_data;
			});

			}
			

		}]);
		
     

	</script>
</body>
</html>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章