选中复选框时在阵列上推送数据,并在取消选中复选框时删除数据

Har*_*sha 2 javascript angularjs

我从表中获取数据并显示为多重检查复选框.当我选中复选框时,将该数据推送到该特定复选框的数组上.但如果未选中,则应从数组中删除相应的数据.如何实现此目的?

HTML:

<div ng-repeat="data in filters.status" >
    <label class="Form-label--tick">
        <input type="checkbox" value="data.id" id="status" ng-model="status" class="Form-label-checkbox"  ng-change="IfCheck(data.id,status)" >
        <span class="Form-label-text"> {{data.status}}</span>
    </label>
</div>
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

<script>
    $scope.IfCheck = function (data, check) {
        if (check) {
            status.push(data);
            $scope.checkedData[0].status = status;
        }
        else {
            var index = $scope.status.indexOf(data);
            $scope.status.splice(index);
        }

    };
</script>
Run Code Online (Sandbox Code Playgroud)

Sha*_*wal 5

这可以写成这样:

var app = angular.module('sa', []);
app.controller('FooCtrl', function($scope) {
  $scope.ids = [];

  $scope.filters = [{
    id: 1,
    status: false
  }, {
    id: 2,
    status: false
  }, {
    id: 3,
    status: false
  }]

  $scope.IfCheck = function(id, check) {
    if (check) {
      $scope.ids.push(id);
    } else {
      var index = $scope.ids.indexOf(id);
      $scope.ids.splice(index, 1);
    }
  };
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="sa" ng-controller="FooCtrl">
  <div ng-repeat="data in filters">
    <label class="Form-label--tick">
      <input type="checkbox" value="data.id" id="status" ng-model="data.status" class="Form-label-checkbox" ng-change="IfCheck(data.id, data.status)">
      <span class="Form-label-text"> {{data.status}}</span>
    </label>
  </div>

  Selected ids: {{ids}}
</div>
Run Code Online (Sandbox Code Playgroud)