带有ng-model angular js的多选复选框

时间:2015-11-23 02:29:15

标签: javascript arrays angularjs angularjs-scope angular-ngmodel

我有以下控制器设置,以便我可以将检查的值添加到数组中,如下所示。



(function (app) {
  'use strict';
  
  app.controller('SimpleArrayCtrl', ['$scope', function SimpleArrayCtrl($scope) {
    // fruits
    $scope.fruits = ['apple', 'orange', 'pear', 'naartjie'];
    
    // selected fruits
    $scope.selection = ['apple', 'pear'];
    
    // toggle selection for a given fruit by name
    $scope.toggleSelection = function toggleSelection(fruitName) {
      var idx = $scope.selection.indexOf(fruitName);
      
      // is currently selected
      if (idx > -1) {
        $scope.selection.splice(idx, 1);
      }
      
      // is newly selected
      else {
        $scope.selection.push(fruitName);
      }
    };
  }]);
})(angular.module('app', []));

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="SimpleArrayCtrl">
        <div class="row">
          <div class="col-md-6">
            <h4>selectables</h4>
            <form class="form-group" novalidate name="test">
              <label ng-repeat="fruitName in fruits" class="checkbox-inline">
                <input type="checkbox" name="selectedFruits[]" value="{{fruitName}}" ng-checked="selection.indexOf(fruitName) > -1" ng-click="toggleSelection(fruitName)"> {{fruitName}}
              </label>
            </form>
          </div>
        </div>

        <div class="row">
          <div class="col-md-6">
            <h4>selection</h4>
            <pre>{{selection|json}}</pre>
          </div>

          <div class="col-md-6">
            <h4>inputs</h4>
            <pre>{{fruits|json}}</pre>
          </div>
          <div class="col-md-6">
            <h4>form</h4>
            <pre>{{test|json}}</pre>
          </div>          
        </div>
      </div>
  </div>
&#13;
&#13;
&#13;

我想要做的是将数组的值绑定到表单中,以便我可以提交数组的内容。

我已将ng-model添加到我的复选框输入中但我似乎只能将true和false返回到我的数组而不是我的值

                <input ng-model="fruitName" type="checkbox" name="selectedFruits[]" value="{{fruitName}}" ng-checked="selection.indexOf(fruitName) > -1" ng-click="toggleSelection(fruitName)">

如何将选择的值绑定到模型并确保单击时仍然符合勾号,这样我可以在提交表单时提交数组的值?

2 个答案:

答案 0 :(得分:0)

ngTrueValue(ng-true-value =“”) 选中时应设置表达式的值。

ngFalseValue(ng-false-value =“”) 未选中时表达式应设置的值。

请参阅此处的示例:https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D

答案 1 :(得分:0)

或者您可以使用this指令。 对我来说很棒 source code