成果展示:
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
textarea{
resize: none;
}
</style>
</head>
<body ng-app="noteApp" ng-controller="NoteController">
<h2>我的笔记</h2>
<textarea cols="30" rows="10" ng-model="message"></textarea>
<div>
<button ng-click="save()">保存</button>
<button ng-click="read()">读取</button>
<button ng-click="delete()">删除</button>
</div>
<p>剩余字数:{{getCount()}}</p>
<script type="text/javascript" src="../../js/angular-1.5.5/angular.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
js:
angular.module('noteApp', [])
.controller('NoteController', function ($scope) {
//console.log($scope.message);
$scope.message = '';
//定义获取剩余字数的方法
$scope.getCount = function () {
//判断输入数据的长度
if(this.message.length > 100){
$scope.message = $scope.message.slice(0, 100);
}
//返回剩余字数的个数
return 100 - $scope.message.length;
};
//定义保存的方法
$scope.save = function () {
alert('note is saved');
//将数据保存到sessionStorage中
sessionStorage.setItem('note_key', JSON.stringify($scope.message));
//将输入内容清空
$scope.message = '';
};
//定义读取的方法
$scope.read = function () {
$scope.message = JSON.parse(sessionStorage.getItem('note_key') || '[]');//对读取null做了处理
};
// 定义删除的方法
$scope.delete = function () {
$scope.message = '';
};
});