angularjs结合localstorage完成一个简单的备忘录

来源:互联网 发布:樱井知香黑人 编辑:程序博客网 时间:2024/05/22 04:50

准备工作

用bower安装需要的js:

bower install angularbower 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:

<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-modeltodoItem关联,使用:

...$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的值即备忘内容contentng-clickremove按钮和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模块

var todoApp=angular.module('todoApp',['LocalStorageModule']);...

controller上传入服务

todoApp.controller('TodoController', function($scope, localStorageService) {...

从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,包含setgetremoveclearAll

3 0
原创粉丝点击