prosource

Angular에서 체크박스를 클릭했을 때 응답하는 방법JS 디렉티브?

probook 2023. 3. 9. 22:08
반응형

Angular에서 체크박스를 클릭했을 때 응답하는 방법JS 디렉티브?

나는 Angular를 가지고 있다.다음 템플릿에서 엔티티 컬렉션을 렌더링하는 JS 지시문:

<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>꽤래 ui UI 。

다음 중 가장 좋은 방법은 무엇입니까?

  • 행을 이 배열에 를 에 합니다).<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??
    };
}

좀 더 구체적으로 말하면, 다음과 같습니다.

  • 있어야 ?니면컨 컨트 ?해? 해?? ???link능하하??? ???
  • 것은 아니라는 을 전제로 ).Query query query query query ( )JS는 필요 없습니다.) DOM 트래버설을 수행하는 가장 좋은 방법은 무엇입니까?없으면 jQuery를 <tr>또는 템플릿의 모든 체크박스를 선택합니다.
  • ★★$event로로 합니다.updateSelection()별로 우아해 보이지 않아요.방금 클릭한 요소의 상태(체크/체크 해제)를 검색하는 더 나은 방법은 없습니까?

감사해요.

이게 내가 이런 식으로 해왔어요.앵글은 필수적인 것보다 돔에 대한 선언적인 조작을 선호하는 경향이 있다(적어도 나는 그것을 가지고 놀았다).

마크업

<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는 되었습니다.

체크박스를 다룰 때ng모델ng 명령을 사용하는 것이 좋습니다.ngModel을 사용하면 체크박스의 온/오프 상태를 엔티티 속성에 바인드할 수 있습니다.

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

" " "가" 체크박스를 꺼줍니다.entity.isChecked도도바바바바다다

이것이 필요한 전부라면 ngClick 또는 ngChange 지시도 필요하지 않습니다.Check All(모두 확인) 체크박스가 있기 때문에 다른 사용자가 체크박스를 켤 때 속성 값을 설정하는 것 이상의 작업을 수행해야 합니다.

체크박스와 함께 ngModel을 사용하는 경우 체크박스와 체크박스가 없는 이벤트를 처리하기 위해 ngClick이 아닌 ngChange를 사용하는 것이 좋습니다.ngChange는 이러한 시나리오만을 위해 이루어집니다.데이터 바인딩에 ngModelController를 사용합니다(ngModelController에 청취자를 추가합니다).$viewChangeListeners배열. 이 배열의 수신기는 모델 값이 설정된 후에 호출되므로 이 문제를 방지할 수 있습니다).

<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;
};

마찬가지로 머리글의 "Check All" 체크박스는 다음과 같습니다.

<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}">

플런커 전체를 보실 수 있습니다.

Liviu의 답변은 나에게 매우 도움이 되었다.이것이 나쁜 형태가 아니길 바라지만 나는 미래에 다른 누군가를 도울 수 있는 바이올린을 만들었다.

다음 두 가지 중요한 요소가 필요합니다.

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

언급URL : https://stackoverflow.com/questions/11872832/how-to-respond-to-clicks-on-a-checkbox-in-an-angularjs-directive

반응형