如何获取多个选中的复选框值

时间:2014-12-13 09:50:30

标签: angularjs checkbox

如何在Angular.js中获取多个选中的复选框值并插入以逗号分隔的数据库(,)?

1 个答案:

答案 0 :(得分:5)

您可以在一系列选项上使用ng-repeat + ng-model

DEMO http://plnkr.co/edit/KcUshc74FZL1npZsKbEO?p=preview

<强> HTML

<body ng-controller="MainCtrl">
  <div class="container">

    <h1>Options</h1>

    <div>

      <div class="form-group" ng-repeat="option in options">
        <label>{{option.name}}</label>
        <input type="checkbox" ng-model="option.value">
      </div>

    </div>

    <hr>
    <button class="btn btn-primary" ng-click="save()">save to database</button>

  </div>


</body>

<强> JS

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.options = [{
    name: 'java',
    value: true,
  }, {
    name: 'c#',
    value: false
  }, {
    name: 'angular',
    value: true
  }, {
    name: 'r',
    value: false
  }, {
    name: 'python',
    value: true
  }, {
    name: 'c++',
    value: true
  }];

  $scope.save = function() {

    var optionsCSV = '';

    $scope.options.forEach(function(option) {

      if (option.value) {

        // If this is not the first item
        if (optionsCSV) {
          optionsCSV += ','
        }
        optionsCSV += option.name;
      }

    })

    // Save the csv to your db (replace alert with your code)
    alert(optionsCSV);

  };


});
相关问题