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

Ang*_*hef 79 javascript angularjs

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

<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>
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,<table>每个行都可以使用自己的复选框单独选择,或者可以使用主复选框一次选择所有行<thead>.很经典的UI.

什么是最好的方式:

  • 选择一行(即选中复选框时,将所选实体的id添加到内部数组,并将CSS类添加到<tr>包含实体以反映其选定状态)?
  • 一次选择所有行?(即对所有行执行前面描述的操作<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??
    };
}
Run Code Online (Sandbox Code Playgroud)

更具体地说,我想知道:

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

谢谢.

Liv*_* T. 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>
Run Code Online (Sandbox Code Playgroud)

并在控制器中

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;
};
Run Code Online (Sandbox Code Playgroud)

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


Kev*_*mey 35

处理复选框时,我更喜欢使用ngModelngChange指令.ngModel允许您将复选框的已选中/未选中状态绑定到实体上的属性:

<input type="checkbox" ng-model="entity.isChecked">
Run Code Online (Sandbox Code Playgroud)

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

如果这就是您所需要的,那么您甚至不需要ngClick或ngChange指令.由于您具有"全部检查"复选框,因此您显然需要做的不仅仅是在有人选中复选框时设置属性的值.

使用带有复选框的ngModel时,最好使用ngChange而不是ngClick来处理已检查和未检查的事件.ngChange就是针对这种情况而制作的.它利用ngModelController进行数据绑定(它为ngModelController的$viewChangeListeners数组添加了一个监听器.在设置模型值调用此数组中的监听器,避免了这个问题).

<input type="checkbox" ng-model="entity.isChecked" ng-change="selectEntity()">
Run Code Online (Sandbox Code Playgroud)

......在控制器中......

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;
};
Run Code Online (Sandbox Code Playgroud)

同样,标题中的"全部检查"复选框:

<th>
    <input type="checkbox" ng-model="model.allItemsSelected" ng-change="selectAll()">
</th>
Run Code Online (Sandbox Code Playgroud)

......而且......

// 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;
    }
};
Run Code Online (Sandbox Code Playgroud)

CSS

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

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

<tr ng-repeat="entity in model.entities" ng-class="{selected: entity.isChecked}">
Run Code Online (Sandbox Code Playgroud)

这里查看完整的Plunker.


VBA*_*ole 11

Liviu的回答对我非常有帮助.希望这不是一个糟糕的形式,但我做了一个小提琴,可能会帮助其他人在未来.

需要的两件重要部分是:

    $scope.entities = [{
    "title": "foo",
    "id": 1
}, {
    "title": "bar",
    "id": 2
}, {
    "title": "baz",
    "id": 3
}];
$scope.selected = [];
Run Code Online (Sandbox Code Playgroud)