准备工作
用bower安装需要的js:
bower install angular
bower install angular-local-storage
html中引用bower_components下对应的js文件:
<script src="js/angular.min.js"></script>
<script src="js/angular-local-storage.js"></script>
说明:npm也可以,直接下载相应js文件或者用cdn也是ok的…
通过angularjs Directive扩展index.html
angular接管整个页面:
<html ng-app="todoApp">
body中的数据由TodoController 来控制:
<body ng-controller="TodoController">
<form ng-submit="add()">
<input placeholder="What you want to do..." type="text" ng-model="todoItem" name="totoItem">
<input type="submit" id="submit" value="add">
</form>
form 提交表单时(ng-submit )执行add() 方法,输入框的内容通过ng-model 与todoItem 关联,使用:
...$scope.todoItem...
添加备忘list
每条备忘中包含的信息:内容content 、日期creDate 、删除按钮。
<ul>
<li ng-repeat="todo in todoList">
<time>{ {todo.creDate} }</time>
<input type="text" ng-model="todo.content">
<span>{ {todo.content} }</span>
<input type="button" value="remove" ng-click="remove($index)">
</li>
</ul>
ng-repeat用来循环输出每一条备忘,ng-model 指定当前input 的值即备忘内容content ,ng-click 将remove 按钮和remove(index) 方法关联。
todo.js
声明app
var todoApp=angular.module('todoApp',[]);
定义controller
todoApp.controller('TodoController',function($scope) {
...
});
定义todoList
$scope.todoList = [];
add方法
$scope.add = function() {
// 如果输入框有值
if ($scope.todoItem) {
// 定义一个空对象
var todoInfo = {};
// 对象的三个属性:时间为创建时时间
todoInfo.creDate = new Date().getMonth() + '/' + new Date().getDate();
todoInfo.content = $scope.todoItem;
todoInfo.status = 'active';
// 将todoInfo添加到todoList头部
$scope.todoList.unshift(todoInfo);
}
}
remove方法
// 删除index位置开始的1个数组元素
$scope.remove = function(index) {
$scope.todoList.splice(index,1);
}
改造todo.js,使用localstorage持久化
两种思路:
- 分别在
$scope.todoList 查询、添加、删除时同步操作localstorage ;
- 监听
$scope.todoList ,当它改变时把$scope.todoList 赋值给localstorage .
第一种方法明显麻烦很多,但当时不知道$scope.$watch 可以做到监听…这里使用$scope.$watch :
添加localstorage模块
controller上传入服务
从localstorage中get数据,如果不为空,赋值给 $scope.todoList
var todoInStore = localStorageService.get('todoList');
$scope.todoList = todoInStore || [];
监听$scope.todoList,当它改变时,使用localstorage的set() 方法
$scope.$watch('todoList',function () {
localStorageService.set('todoList',$scope.todoList);
},true);
over
这样就实现了一个简版的备忘录,只要缓存没有被清理,备忘会一直在。
另外angular local storage还提供了一些方法供开发者使用:
-
remove(key):匹配key删除localStorage条目
-
clearAll():删除全部localStorage
-
isSupported:检测浏览器是否支持localStorage
-
cookie:操作cookie的方法同localStorage,包含set 、get 、remove 、clearAll 。
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|