码路上的Randy

JavaScripter,兼职高三狗

导航

使用AngularJS + StoreDB快速建立基于localStorage的Todo应用(一)

我们可以用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的巨大潜力。

下一篇我们开始写“已读”功能。

posted on 2014-01-17 10:59  卢涛南  阅读(2717)  评论(2编辑  收藏  举报