angular小练习之我的笔记

angular小练习,实现简单的笔记保存、读取和删除,并同步剩余字数,其中涉及到了数据存储方面的知识;

html5页面很简单,就是一个文本框,加上三个button分别是保存、读取和删除;

html代码:

<body ng-app="myApp" ng-controller="NoteCtrl">
  <h2>我的学习笔记</h2>
  <textarea cols="30" rows="10" ng-model="msg"></textarea>
  <div>
    <button ng-click="save()">保存</button>
    <button ng-click="read()">读取</button>
    <button ng-click="remove()">删除</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>

js代码:

angular.module("myApp",[])
        .controller("NoteCtrl",['$scope',function ($scope) {
          //初始化msg数据
          $scope.msg = "";
          //定义计算剩余字数的方法
          $scope.getCount = function () {
            //判断用户输入的内容的长度
            if($scope.msg.length > 100){
                $scope.msg = $scope.msg.slice(0,100);
            }
            return 100 - $scope.msg.length;
          };
          //定义保存数据的方法
          $scope.save = function () {
            alert('note has been saved !');
            localStorage.setItem("note_key",JSON.stringify($scope.msg));
            $scope.msg = "";
          };
          $scope.read = function () {
              $scope.msg = JSON.parse(localStorage.getItem("note_key") || "[]");//注意:这里不能是{}也不能是''
          };
          $scope.remove = function () {
            localStorage.removeItem("note_key");
            $scope.msg = "";
          };
        }]);

猜你喜欢

转载自blog.csdn.net/qq_31207499/article/details/81409700
今日推荐