首页 > 代码库 > 一个利用HTML5 localStorage功能的todo应用(angularJs+Bootstrap)

一个利用HTML5 localStorage功能的todo应用(angularJs+Bootstrap)

今天在网上看到一个简单的todo应用,使用angularJs做前端数据绑定,利用localStorage来存储数据,觉得挺有意思的。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html ng-app="todoApp">  <head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/><script src="/js/angular.js" type="text/javascript"></script><script src="//netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js" type="text/javascript"></script><link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" type="text/css"/><script type="text/javascript" src="/less/js/app.js"></script><style>  .center-grey{ background:#f2f2f2; margin-top:20;  }  .top-buffer {  margin-top:20px;   }  button{  display: block;   width: 100%;  }</style><title>Angular Todo Note App</title>  </head>  <body><div class="container center-grey" ng-controller="TodoController">  <div class="row top-buffer" ><span class="col-md-3"></span><span class="col-md-5">  <input class="form-control" type="text" ng-model="note" placeholder="Add a note here"/> </span><span class="col-md-1">  <button ng-click="createNote()" class="btn btn-success">Add</button></span><span class="col-md-3"></span>  </div>  <div class="row top-buffer" ><span class="col-md-3"></span><span class="col-md-6">  <ul class="list-group"><li ng-repeat="note in notes track by $index" class="list-group-item">  <span>{{note}}</span></li>  </ul></span><span class="col-md-3"></span>  </div></div>  </body></html>

ng-app声明了使用todoApp作为model

ng-controller声明了TodoController作为控制器

ng-model="note" 对输入框input进行了数据绑定,绑定到了$scope.note

ng-click="createNote"对函数(对象)进行了绑定,绑定到了$scope.createNote = function(){...}

ng-repeat = "note in notes track by $index" 以及{{note}} 是不是看上去很眼熟,对了,就是angularJs的循环遍历的写法,列出所有的notes数组里的数据

下面就是todoApp的js寇丁,controller‘TodoController‘传入$scope和notesFactory服务,

object.keys遍历localStorage里所有的key-value键值对

var todoApp = angular.module(‘todoApp‘,[]);todoApp.controller(‘TodoController‘,function($scope,notesFactory){    $scope.notes = notesFactory.get();    $scope.createNote = function(){        notesFactory.put($scope.note);        $scope.note=‘‘;        $scope.notes = notesFactory.get();    }});todoApp.factory(‘notesFactory‘,function(){    return {    put: function(note){            localStorage.setItem(‘todo‘ + (Object.keys(localStorage).length + 1), note);    },    get: function(){        var notes = [];        var keys = Object.keys(localStorage);        for(var i = 0; i < keys.length; i++){            notes.push(localStorage.getItem(keys[i]));        }        return notes;    }           };})

BTW,通过firefox的开发者工具可以查看修改删除当前页面的localStorage内容,具体方法请猛戳这里

最后想说的是,angularJS真是一个好东西啊