![]() |
| 圖1. 側欄選單 |
2015年5月19日 星期二
Hybrid Apps開發系列之7.2:SideMenu側欄選單(Spotify歌曲試聽範例)
隨著Apps功能越來越豐富,為讓使用者能有較佳的介面操作體驗,通常會以「側欄選單」(sidemenu, 如圖) 的方式解決。
「側欄選單」和「頁籤」(參考Hybrid Apps開發系列之4.4:多頁面App程式 (天氣app-非線上版))一樣都是屬於主頁面類型,實作時會將「側欄選單」所在頁面設定為parent state,其他頁面則共用「側欄選單」所在的parent state。
2015年4月27日 星期一
Hybrid Apps開發系列之5.1:資料模型與自訂services(重構天氣app線上版)
Ionic/AngularJS apps透過$scope變數可以定義資料模型 (data model) 變數供前端頁面 (views)使用,而在controller端,則會將資料模型變數設定為數值、陣列甚至是透過web services得到的資料。然而,如果有資料處理、頁面共用資料模型等更複雜的運作方式時,應該呼叫.factory()採用「自訂services」的方式,將資料處理等相關程式碼打包進factory,供$scope以及前端頁面運用,如下圖所示:
如圖1,factory可將資料庫、web services、或是一般JavaScript物件包裹起來,建立資料處理服務,提供$scope與前端頁面使用。Factory就相當於apps的資料層 (data layer)。
![]() |
| 圖1.各種資料來源可透過factory進行管理 |
Factory基本格式
Ionic/AngularJS模組都可建立factory,做為資料層,基本格式如下:angular.module('starter',['ionic])
.factory('serviceName',function(){
return {}
}
)
2015年4月24日 星期五
Hybrid Apps開發系列之4.6:多頁面App程式 (天氣app-線上即時版)
使用$http模組,可透過HTTP即時取得資料後,稍微修改Hybrid Apps開發系列之4.4:多頁面App程式 (天氣app-非線上版) 的離線版程式,便可改為線上即時版。
唯一要修改的是controllers.js,修改後如下:
唯一要修改的是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
Hybrid Apps開發系列之4.5:以HTTP連線取得JSON資料
開放資料當道,許多都可透過HTTP連線方式取得JSON格式資料,前文Hybrid Apps開發系列之4.4:多頁面App程式 (天氣app-非線上版)便以open weather map,離線取得天氣資料。但如果要線上即使取得資料,則必須使用AngularJS的$http模組。
$http連線使用方式如下:
$http連線取得JSON資料
$http實際上是發出http要求,進而取得回應資料。如果格式是JSON,在JavaScript中便可直接使用,其他格式則不一定。$http連線使用方式如下:
$http.get("http://url/service", { params: { "key1": "value1", "key2": "value2" } })
.success(function(response) {
// 處理http回應資料; response為回傳資料
})
.error(function(err) {
// 連線錯誤
});
另一種寫法則是:$http.get("http://url/service", { params: { "key1": "value1", "key2": "value2" } })
.then(function(response) {
// 建立天氣資料模型變數,response.data為回傳資料
}, function(err) {
// 連線錯誤
});
兩者有所差別,可參考此討論串。在此建議用
.then(function(resp),function(err))
訂閱:
文章 (Atom)

