如何响应AngularJS指令中复选框的点击?

时间:2012-08-08 20:41:41

标签: javascript angularjs

我有一个AngularJS directive,它在以下模板中呈现实体集合:

<table class="table">
  <thead>
    <tr>
      <th><input type="checkbox" ng-click="selectAll()"></th>
      <th>Title</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="e in entities">
      <td><input type="checkbox" name="selected" ng-click="updateSelection($event, e.id)"></td>
      <td>{{e.title}}</td>
    </tr>
  </tbody>
</table>

正如您所看到的,它是<table>,其中每行可以使用自己的复选框单独选择,或者可以使用<thead>中的主复选框一次选择所有行。相当经典的用户界面。

最好的方法是:

  • 选择一行(即选中复选框时,将所选实体的ID添加到内部数组,并将CSS类添加到包含实体的<tr>以反映其选定状态)?< / LI>
  • 一次选择所有行? (即对<table>
  • 中的所有行执行上述操作

我目前的实现是在我的指令中添加一个自定义控制器:

controller: function($scope) {

    // Array of currently selected IDs.
    var selected = $scope.selected = [];

    // Update the selection when a checkbox is clicked.
    $scope.updateSelection = function($event, id) {

        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');
        if (action == 'add' & selected.indexOf(id) == -1) selected.push(id);
        if (action == 'remove' && selected.indexOf(id) != -1) selected.splice(selected.indexOf(id), 1);

        // Highlight selected row. HOW??
        // $(checkbox).parents('tr').addClass('selected_row', checkbox.checked);
    };

    // Check (or uncheck) all checkboxes.
    $scope.selectAll = function() {
        // Iterate on all checkboxes and call updateSelection() on them??
    };
}

更具体地说,我想知道:

  • 上面的代码是属于控制器还是属于link函数?
  • 鉴于jQuery不一定存在(AngularJS不需要它),进行DOM遍历的最佳方法是什么?如果没有jQuery,我很难选择给定复选框的父<tr>,或者选择模板中的所有复选框。
  • $event传递给updateSelection()似乎并不优雅。是否有更好的方法来检索刚刚单击的元素的状态(选中/取消选中)?

谢谢。

3 个答案:

答案 0 :(得分:122)

这就是我一直在做这种事情的方式。 Angular倾向于支持对dom的声明性操作而不是强制性操作(至少那是我一直在使用它的方式)。

标记

<table class="table">
  <thead>
    <tr>
      <th>
        <input type="checkbox" 
          ng-click="selectAll($event)"
          ng-checked="isSelectedAll()">
      </th>
      <th>Title</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="e in entities" ng-class="getSelectedClass(e)">
      <td>
        <input type="checkbox" name="selected"
          ng-checked="isSelected(e.id)"
          ng-click="updateSelection($event, e.id)">
      </td>
      <td>{{e.title}}</td>
    </tr>
  </tbody>
</table>

在控制器中

var updateSelected = function(action, id) {
  if (action === 'add' && $scope.selected.indexOf(id) === -1) {
    $scope.selected.push(id);
  }
  if (action === 'remove' && $scope.selected.indexOf(id) !== -1) {
    $scope.selected.splice($scope.selected.indexOf(id), 1);
  }
};

$scope.updateSelection = function($event, id) {
  var checkbox = $event.target;
  var action = (checkbox.checked ? 'add' : 'remove');
  updateSelected(action, id);
};

$scope.selectAll = function($event) {
  var checkbox = $event.target;
  var action = (checkbox.checked ? 'add' : 'remove');
  for ( var i = 0; i < $scope.entities.length; i++) {
    var entity = $scope.entities[i];
    updateSelected(action, entity.id);
  }
};

$scope.getSelectedClass = function(entity) {
  return $scope.isSelected(entity.id) ? 'selected' : '';
};

$scope.isSelected = function(id) {
  return $scope.selected.indexOf(id) >= 0;
};

//something extra I couldn't resist adding :)
$scope.isSelectedAll = function() {
  return $scope.selected.length === $scope.entities.length;
};

编辑getSelectedClass()期望整个实体,但它仅使用实体的ID进行调用,现在已更正

答案 1 :(得分:35)

我更喜欢在ngModel时使用ngChangedealing with checkboxes指令。 ngModel允许您将复选框的已选中/未选中状态绑定到实体上的属性:

<input type="checkbox" ng-model="entity.isChecked">

每当用户选中或取消选中该复选框时,entity.isChecked值也会改变。

如果您只需要这些,那么您甚至不需要ngClick或ngChange指令。因为你有&#34;全部检查&#34;复选框,你显然需要做的不仅仅是在有人检查复选框时设置属性的值。

将ngModel与复选框一起使用时,最好使用ngChange而不是ngClick来处理已检查和未检查的事件。 ngChange就是针对这种情况而制作的。它利用ngModelController进行数据绑定(它为ngModelController的$viewChangeListeners数组添加了一个监听器。在模型之后,该数组中的监听器被称为已设置值avoiding this problem)。

<input type="checkbox" ng-model="entity.isChecked" ng-change="selectEntity()">

......并且在控制器......

var model = {};
$scope.model = model;

// This property is bound to the checkbox in the table header
model.allItemsSelected = false;

// Fired when an entity in the table is checked
$scope.selectEntity = function () {
    // If any entity is not checked, then uncheck the "allItemsSelected" checkbox
    for (var i = 0; i < model.entities.length; i++) {
        if (!model.entities[i].isChecked) {
            model.allItemsSelected = false;
            return;
        }
    }

    // ... otherwise ensure that the "allItemsSelected" checkbox is checked
    model.allItemsSelected = true;
};

同样,&#34;全部检查&#34;标题中的复选框:

<th>
    <input type="checkbox" ng-model="model.allItemsSelected" ng-change="selectAll()">
</th>

......和......

// Fired when the checkbox in the table header is checked
$scope.selectAll = function () {
    // Loop through all the entities and set their isChecked property
    for (var i = 0; i < model.entities.length; i++) {
        model.entities[i].isChecked = model.allItemsSelected;
    }
};

<强> CSS

  

将CSS类添加到包含实体的<tr>以反映其选定状态的最佳方法是什么?

如果您使用ngModel方法进行数据绑定,那么您需要做的就是将ngClass指令添加到<tr>元素,以便在实体属性发生更改时动态添加或删除该类:

<tr ng-repeat="entity in model.entities" ng-class="{selected: entity.isChecked}">

查看完整的Plunker here

答案 2 :(得分:11)

Liviu的回答对我非常有帮助。希望这不是一个糟糕的形式,但我做了一个fiddle,可以帮助其他人将来。

需要的两个重要部分是:

    $scope.entities = [{
    "title": "foo",
    "id": 1
}, {
    "title": "bar",
    "id": 2
}, {
    "title": "baz",
    "id": 3
}];
$scope.selected = [];