Adding and deleting records in simple angular exercises

       Use angular to implement simple record addition and deletion functions. There are two ways to delete records. One is to directly traverse the record array and judge each object in the array. If it is selected, it is deleted, but this method needs to be noted that , When there are two consecutive selected records, the selected records will be missed, because when deleting the array, the corresponding subscript of each object behind the deleted object will be reduced by 1, and the order of traversal is to delete the object The subscript continues to traverse backwards, so an object behind the deleted object will be missed. The solution is to call the delete function again after the delete operation; the second method is to assign the record array to an intermediate variable and then record Empty the array, and then traverse the intermediate variables, add the unselected objects to the record array, this method will not miss any object in the array;

HTML code snippet:

<body ng-app="todoApp" >
<div ng-controller="MyCtrl">
  <h2>我的备忘录</h2>
  <div>
    <input type="text" ng-model="newTodo">
    <button ng-click="add()">添加</button>
  </div>
  <div ng-repeat="todo in todos">
    <input type="checkbox" ng-model="todo.isChecked">
    <span>{{todo.name}}</span>
  </div>
  <button ng-click="remove()">删除选中的按钮</button>
</div>


<script type="text/javascript" src="../../js/angular-1.5.5/angular.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>

JS code:

angular.module('todoApp',[])
        .controller('MyCtrl',['$scope',function ($scope) {
          $scope.todos = [
            {name:'吃饭',isChecked:false},
            {name:'睡觉',isChecked:false},
            {name:'打豆豆',isChecked:false}
          ];
          //定义添加记录的方法
          $scope.add = function () {
            //判断用户输入的内容是否合法
            if(! $scope.newTodo){
              alert("输入的内容不能为空");
              return;
            }
            //收集整理数据
            var obj = {
              name:$scope.newTodo,
              isChecked:false
            };
            $scope.newTodo = "";
            $scope.todos.unshift(obj);
          };
          //定义删除的办法
         /* $scope.remove = function () {
            $scope.todos.forEach(function (item,index) {
              //找到选中的对象
              if(item.isChecked){
                $scope.todos.splice(index,1);
                $scope.remove();
              }
            })
          };*/
         $scope.remove = function () {
             var oldTodo = $scope.todos;
             $scope.todos = [];
             oldTodo.forEach(function (item,index) {
               if(! item.isChecked){
                   $scope.todos.push(item);
               }
             })
         }
        }])
Published 50 original articles · Likes5 · Visits 20,000+

Guess you like

Origin blog.csdn.net/qq_31207499/article/details/81410149