2015年4月24日 星期五

Hybrid Apps開發系列之4.6:多頁面App程式 (天氣app-線上即時版)

使用$http模組,可透過HTTP即時取得資料後,稍微修改Hybrid Apps開發系列之4.4:多頁面App程式 (天氣app-非線上版) 的離線版程式,便可改為線上即時版。

唯一要修改的是controllers.js,修改後如下:
  1. angular.module('starter.controllers',[])
  2. .controller('homeCtrl',function($scope,$location){
  3. $scope.citys = citys;
  4. $scope.showWeather = function(index){
  5. $location.path('/tab/home/'+index);
  6. }
  7. })
  8. .controller('settingsCtrl',function($scope){
  9. $scope.citys = citys;
  10. })
  11. .controller('weatherCtrl', function ($scope, $stateParams, $http) {
  12. $scope.city = citys[$stateParams.id];
  13. $scope.img_base_url = image_base_url;
  14. $http.get('http://api.openweathermap.org/data/2.5/weather',
  15. {params: {'q': $scope.city.q}})
  16. .then(function (response) {
  17. $scope.weather = response.data;
  18. }, function (err) {
  19. alert("Error!!")
  20. })
  21. })
  22. var citys = [
  23. {name: "台北", q: "Taipei", on: true},
  24. {name: "台中", q: "Taichung", on: true},
  25. {name: "台南", q: "Tainan", on: true},
  26. {name: "高雄", q: "Kaohsiung", on: true},
  27. {name: "花蓮", q: "Hualian", on: true},
  28. ]
  29. var image_base_url = "http://openweathermap.org/img/w/"; // open weather api icon
  • 第11行:加入$http模組服務的controller。
  • 第12行:根據$stateParams.id傳遞過來的值,從第22行citys陣列取得城市資料。
  • 第14行:直接呼叫$http.get()取得資料。
  • 第15行:參數則用城市的'q'參數值(英文城市名),此為open weather map天氣api的要求。
其餘檔案內容可參考Hybrid Apps開發系列之4.4:多頁面App程式 (天氣app-非線上版) 。

JS Bin線上版本

沒有留言:

張貼留言