標籤:trigger.io todo trigger forge
用Trigger.io改進移動Angular.js應用
chszs,轉載需註明。部落客頁:http://blog.csdn.net/chszs
Trigger.io Forge可以讓我們使用最新、最好的Web技術來開發本地行動裝置 App。
本文展示了開發一個簡單的Angular.js應用樣本,並使用Forge模組增強此應用,包括:
1)使用forge.prefs來增加離線能力和持久化能力
2)使用forge.topbar來增加本地topbar和動作按鈕
3)使用forge.tabbar來實現視圖間的導航
本樣本是做一個TODO列表。
一、建立一個Forge應用
第一步是建立一個Forge應用,要確保APP可以離線運行,我們必須在當地套件含angular.min.js和bootstrap.css檔案。運行代碼後可以看到上面的介面。
整個應用的結構如下:
index.html的內容:
<!doctype html><html ng-app><head><script src="js/angular-1.0.1.min.js"></script><script src="js/todo.js"></script><link rel="stylesheet" href="css/bootstrap.css"><style>.done-true {text-decoration: line-through;color: grey;}</style></head><body><h2>Todo</h2><div ng-controller="TodoCtrl"><span>{{remaining()}} of {{todos.length}} remaining</span>[ <a href="" ng-click="archive()">archive</a> ]<ul class="unstyled"><li ng-repeat="todo in todos"><input type="checkbox" ng-model="todo.done"><span class="done-{{todo.done}}">{{todo.text}}</span></li></ul><form ng-submit="addTodo()"><input type="text" ng-model="todoText"size="30" placeholder="add new todo here"><input class="btn-primary" type="submit" value="add"></form></div></body></html>
二、持久化資料
現在HTML5樣本的程式已經完成,那麼我們可以使用Forge的擴充功能來改進此應用。
我們要做的第一件事是使用prefs模組來持久化TODO列表。無論TODO列表是否得到更新,都需要儲存它。代碼如下:
forge.prefs.set(“todos”, $scope.todos);
當APP運行時,就可以用儲存的TODO列表資料恢複TODO列表了。
// 用儲存的資料恢複TODO列表forge.prefs.get("todos", function(todos{// 更新Angular模型, $apply確保視圖得到更新$scope.$apply(function(){if(todos){$scope.todos = todos;} else{$scope.todos = [{text:‘learn angular‘, done:true},{text:‘build an angular app‘, done:false},{text:‘extend angular app to work with Forge‘, done:false}];}});}));要注意的是這塊代碼$scope.$apply(function () { ... }),它告訴Angular,此代碼塊會修改模型,代碼運行後視圖應該得到更新。沒有這塊代碼,一旦prefs被載入後,使用者是看不到更新的。
三、添加一個topbar
我們還可以為APP的介面添加一個topbar,即使TODO列表太長,導致頁面卷邊,topbar也總是可見的。要做到這一點,我們可以把index.html的內容<h2>Todo</h2>刪除,添加topbar模組。
topbar模組允許我們添加按鈕事件,我們可以在頁面上移除存檔的連結,還可以添加本地按鈕來存檔已完成的任務。代碼如下:
forge.topbar.addButton({icon: "img/accept.png"}, function(){$scope.$apply($scope.archive);});
四、添加一個tabbar
如同topbar一樣,我們還可以使用Forge添加一個本地tabbar。藉此,我們將第二頁添加到TODO列表應用中,這頁的功能是允許使用者查看以前歸檔的任務。
要做到這一點,我們添加一些HTML代碼以及幾個JavaScript函數來實現兩頁之間的切換,TODO列表的持久化仍舊使用prefs實現。代碼如下:
// 添加Forge tabbar按鈕forge.tabbar.addButton({icon: "img/list.png",text: "Todo list"}, function(button){button.setActive();button.onPressed.addListener(function(){$scope.$apply($scope.showList);});});forge.tabbar.addButton({icon: "img/archive.png",text: "Archive"}, function(button){button.onPressed.addListener(function(){$scope.$apply($scope.showArchive);});})
五、總結
我們現在有了一個簡單的TODO列表應用,在Forge運行,並同時利用了Angular.js和Forge模組的優點,還允許訪問本地特性,並同時支援Android和iOS的運行。
完整的源碼在GitHub,見:https://github.com/Connorhd/Forge-Angular-Todo
用Trigger.io改進移動Angular.js應用