我們可以用StoreDB配合AngularJS非常簡單地做出功能強大的SPA(Single Page Application),今天我們來試試做出一個最簡單的Todo應用。
STEP1.
首先需要在目錄中獲得AngularJS和StoreDB的腳本文件,推薦使用bower:
$ bower install angular
$ bower install storedb
或在github上獲取:https://github.com/djyde/StoreDB
運行后在目錄中創建“todo.html”,現在的目錄結構如下:
在HTML文件中引入文件:
<script type="text/javascript" src="bower_components/storedb/storedb.js"></script> <script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
STEP2.
到這里我們已經作好了依賴准備,現在可以開始編寫代碼了。
<html> <head> <script type="text/javascript" src="bower_components/storedb/storedb.js"></script> <script type="text/javascript" src="bower_components/angular/angular.min.js"></script> </head> <body> <div> <input placeholder="What u have to do?..."> <button>Add</button> <ul> <li></li> </ul> </div> </body> </html>
效果:
顯然,我們要在ul中遍歷出所有todo項,button用來插入一條新的項。不過這些都要交給Angular來做。
STEP3.
接下來我們要做出增加一條todo項的功能,要在<div>中部署Angular:
<div ng-app="todo" ng-controller="todoCtrl"> <input ng-model="cont" placeholder="What u have to do?..."/> <button ng-click="add()">add</button> <ul ng-repeat="list in lists"> <li>{{list.cont}}</li> </ul> </div>
有AngularJS基礎的朋友應該不難看懂以上代碼所作出的更改。
控制器todoCtrl代碼:
var app = angular.module('todo',[]); app.controller('todoCtrl',function($scope){ $scope.lists = storedb('todo').find(); $scope.add = function(){ storedb('todo').insert({"cont":$scope.cont,"isDone":"false"},function(err){ if(!err){ $scope.lists = storedb('todo').find(); } else { alert(err) } }) } })
storedb('todo').find()會返回一個包集合中所有文檔的數組,我們把它賦值給$scope.lists,這樣我們就能在<ul>中訪問這個數組。
add是負責插入操作的函數,插入一條todo項也就是在'todo'集合中插入一條新的文檔,在StoreDB中,插入新文檔的方法是:
storedb('todo').insert({"cont":$scope.cont,"isDone":"false"},function(err){ if(!err){ $scope.lists = storedb('todo').find(); } else { alert(err) }
})
其中cont為todo內容,isDone為已讀狀態。
插入成功后通過回調函數再把最新的文檔數組賦值到$scope.lists,這時AngularJS的雙向數據綁定會直接更新UI,在ul中顯示最新的todo項。
效果圖:
插入功能就這么寫好了,現在嘗試刷新頁面、關閉瀏覽器,數據都沒有丟失,因為localStorage數據只有在清除緩存時才會被刪除。到這里也許你已經能看出AngularJS + StoreDB的巨大潛力。
下一篇我們開始寫“已讀”功能。