选中复选框时显示消息,并在取消选中时显示另一条消息

时间:2017-06-09 07:50:44

标签: javascript angularjs checkbox

我在Javascript / AngularJS中相当新,并想玩它来学习/理解这些语言。在Angular网站上有一些基本的待办事项列表脚本我想稍微改变一下。我把它改成了我需要学习的东西的清单。当我勾选复选框时,我得到了一些信息,“做得好!”。但是当我取消选中它时,会弹出相同的消息并且我想改变一些类似“你确定吗?”的内容。

我花了几个小时寻找答案,但找不到答案,所以我希望有人可以帮我弄清楚如何做到这一点。这是我的代码:

HTML:

      <div ng-controller="TodoListController as todoList">
        <span>Nog {{todoList.remaining()}} van de {{todoList.todos.length}} te gaan!</span>
        <!--[ <a href="" ng-click="todoList.archive()">archive</a> ]-->
        <ul class="unstyled">
          <li ng-repeat="todo in todoList.todos">
            <label class="checkbox">
              <input type="checkbox" onclick="alert('Well done!')" ng-model="todo.done">
              <span class="done-{{todo.done}}">{{todo.text}}</span>
            </label>
          </li>
        </ul>
      </div> <!--einde ng-controller -->

AngularJS代码:

todoList.remaining = function() {
  var count = 0;
  angular.forEach(todoList.todos, function(todo) {
    count += todo.done ? 0 : 1;
  });
  return count;
};

todoList.archive = function() {
  var oldTodos = todoList.todos;
  todoList.todos = [];
  angular.forEach(oldTodos, function(todo) {
    if (!todo.done) todoList.todos.push(todo);
  });
};

如果遗漏了什么,请告诉我! 提前谢谢!

1 个答案:

答案 0 :(得分:0)

以下是您的更新代码:

<div ng-controller="TodoListController as todoList">
        <span>Nog {{todoList.remaining()}} van de {{todoList.todos.length}} te gaan!</span>
        <!--[ <a href="" ng-click="todoList.archive()">archive</a> ]-->
        <ul class="unstyled">
          <li ng-repeat="todo in todoList.todos">
            <label class="checkbox">
              <input type="checkbox" onclick="showAlert(todo.done)" ng-model="todo.done">
              <span class="done-{{todo.done}}">{{todo.text}}</span>
            </label>
          </li>
        </ul>
      </div> <!--einde ng-controller -->

AngularJs代码:

todoList.remaining = function() {
  var count = 0;
  angular.forEach(todoList.todos, function(todo) {
    count += todo.done ? 0 : 1;
  });
  return count;
};

  $scope.showAlert = function(isSuccess){
               if(isSuccess)
                  alert('Well done!')
               else
                 alert('Unchecked')
                };
todoList.archive = function() {
  var oldTodos = todoList.todos;
  todoList.todos = [];
  angular.forEach(oldTodos, function(todo) {
    if (!todo.done) todoList.todos.push(todo);
  });
};