2015年4月24日 星期五

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

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

唯一要修改的是controllers.js,修改後如下:
angular.module('starter.controllers',[])
        .controller('homeCtrl',function($scope,$location){
            $scope.citys = citys;
            $scope.showWeather = function(index){                
                $location.path('/tab/home/'+index);
            }
        })
        .controller('settingsCtrl',function($scope){
            $scope.citys = citys;
        })          
        .controller('weatherCtrl', function ($scope, $stateParams, $http) {
            $scope.city = citys[$stateParams.id];
            $scope.img_base_url = image_base_url;
            $http.get('http://api.openweathermap.org/data/2.5/weather',
                    {params: {'q': $scope.city.q}})
                    .then(function (response) {
                        $scope.weather = response.data; 
                    }, function (err) {
                        alert("Error!!")
                    })
        })
var citys = [
    {name: "台北", q: "Taipei", on: true},
    {name: "台中", q: "Taichung", on: true},
    {name: "台南", q: "Tainan", on: true},
    {name: "高雄", q: "Kaohsiung", on: true},
    {name: "花蓮", q: "Hualian", on: true},
]
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線上版本氣象App

沒有留言:

張貼留言