【问题标题】:multi select check box with ng-model angular js带有 ng-model angularjs 的多选复选框
【发布时间】:2016-02-25 01:51:15
【问题描述】:

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

(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>

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

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

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

如何将 selection 的值绑定到模型,并确保在单击时仍然可以使用刻度,以便在提交表单时提交数组的值?

【问题讨论】:

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


    【解决方案1】:

    ngTrueValue (ng-true-value="") 选择表达式时应设置的值。

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

    在此处查看示例:https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D

    【讨论】:

      【解决方案2】:

      或者你可以使用this 指令。 对我很好 source code

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-07-25
        • 1970-01-01
        • 2017-09-28
        • 2017-08-13
        • 2016-09-09
        • 2020-07-05
        • 2017-01-31
        相关资源
        最近更新 更多