提交表单时,获取角度js中动态复选框的值

时间:2016-09-19 06:59:48

标签: angularjs forms checkbox

在我的HTML表单中有5个复选框。如何在表单提交时检查是否选中了哪些复选框?

3 个答案:

答案 0 :(得分:1)

我正在使用这段小代码。随意拿它。

在您的控制器中:

$scope.sentinel = [];

$scope.toggleSelection = function(value) {              
            // Bit trick, equivalent to "contains"
            if (~$scope.sentinel.indexOf(value)) {
                var idx = $scope.sentinel.indexOf(value);
                $scope.sentinel.splice(idx, 1);
                return;
            }

            $scope.sentinel.push(value);
        };

然后在你的HTML中:

<span ng-repeat="key in $scope.yourarray">
    <md-checkbox style="margin-left:30px;" aria-label="Select item"
    ng-click="toggleSelection(key)"><span>{{ key }}</span></md-checkbox>
    <br/>
</span>

这允许您拥有任意大小的数组,并使用sentinel数组来注册已检查的值。如果再次选中一个复选框,toogleSelection将阻止您再次添加值。

答案 1 :(得分:0)

您可以定义数组值并映射到html。

$scope.checkbox = [];

HTML

<input ng-model="checkbox[0] type="checkbox" />
<input ng-model="checkbox[1] type="checkbox" />
<input ng-model="checkbox[2] type="checkbox" />
<input ng-model="checkbox[4] type="checkbox" />

或者您可以将复选框定义为对象,并将复选框[索引]更改为复选框[名称]。

答案 2 :(得分:0)

您可以使用Angular.js的Checklist-model。这非常有用:

var app = angular.module("app", ["checklist-model"]);
app.controller('Ctrl1', function($scope) {
  $scope.roles = [
    'guest', 
    'user', 
    'customer', 
    'admin'
  ];
  $scope.user = {
    roles: ['user']
  };
  $scope.checkAll = function() {
    $scope.user.roles = angular.copy($scope.roles);
  };
  $scope.uncheckAll = function() {
    $scope.user.roles = [];
  };
  $scope.checkFirst = function() {
    $scope.user.roles.splice(0, $scope.user.roles.length); 
    $scope.user.roles.push('guest');
  };
  $scope.showCheckedOnes = function() {
    var checkedBoxes = "";
    for (var i = 0; i < $scope.user.roles.length; i++) {
      checkedBoxes += $scope.user.roles[i] + " ";
    }
    alert(checkedBoxes);
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://vitalets.github.io/checklist-model/checklist-model.js"></script>

  <div ng-app="app">
    <div ng-controller="Ctrl1">

      <label ng-repeat="role in roles">
        <input type="checkbox" checklist-model="user.roles" checklist-value="role"> {{role}}
      </label>

    <div>
  <div>
  <button ng-click="checkAll()" style="margin-right: 10px">Check all</button>
  <button ng-click="uncheckAll()" style="margin-right: 10px">Uncheck all</button>
  <button ng-click="checkFirst()" style="margin-right: 10px">Check first</button>
  <button ng-click="showCheckedOnes()" style="margin-right: 10px">Show checked ones</button>