通过选择ng-repeat复选框添加数组

时间:2016-08-18 18:33:09

标签: javascript angularjs arrays angularjs-ng-repeat angular-ngmodel

我在提交表单中添加适当的数据时遇到了一个小问题。此表单的所有文件都来自http请求,其中一个字段是类别,此字段的值来自另一个http请求,借助于ng-repeat我在表单中呈现值。值具有ID和名称。我需要在表单中发送类似ID的数组,如new ArrayList<>(users).stream().forEach(u -> users.remove(u)); ,其中数字是所选类别的ID。问题是我的数组看起来像categories: [1,4,5,7]什么是完全错误的。我的问题是plunker。我想我的ng模型有问题,但找不到确切的结果。所以有人能告诉我我错过了什么吗?

代码

categories: [1: true, 5, true ]

html

     $scope.category = [
    {"id":5,"name":"Data Quality"},
    {"id":2,"name":"Documentation"},
    {"id":4,"name":"Drug Supply"},
    {"id":8,"name":"Enrollment"},
    {"id":3,"name":"Patient Safety"},
    {"id":7,"name":"Randomization"},
    {"id":9,"name":"Site Performance"},
    {"id":1,"name":"Study Conduct"},
    {"id":6,"name":"Technology Related"}
    ]

    $scope.sendData = {}

    $scope.vmodel = angular.copy($scope.sendData);

 $scope.onSubmit = function (event) {
                if (event.id == null || event.id == 0) {
                    console.log(event)
                }
            };

2 个答案:

答案 0 :(得分:1)

<label class="form-check-label col-xs-4 no-padding" for="categories" ng-true-value="'{{cat.name}}'" ng-false-value="''">
            {{ cat.name }}
            <input type="checkbox" class="form-check-input col-xs-2"  ng-click="add(cat.id)" id="categories" />
          </label>


$scope.sendData = {
    categories: []
  }

  $scope.add = function(id) {
    if ($scope.sendData['categories'].indexOf(id) == -1) {
      $scope.sendData.categories.push(id);
    } else {
      $scope.sendData.categories.splice($scope.sendData['categories'].indexOf(id), 1);

    }
    console.log($scope.sendData);



  }

  $scope.onSubmit = function(event) {

    console.log($scope.sendData)
  };

答案 1 :(得分:0)

假设您的输入为{“5”:true,“7”:true,“8”:true,“9”:true}。我看到两个选择:

1)变换对象:

$scope.$watch('vmodel.categories', function(val) { 
  if (val) 
    $scope.selected = Object.keys(val)
    console.log($scope.selected)  // output is $scope.selected
}, true)

2)改变你监听事件的方式

<!-- html --> 
<input type='checkbox' ng-click='toggle(cat)' />


// js 
$scope.selected = [] 
$scope.toggle = function(cat) {
  if ($scope.vmodel.categories[cat]) 
    $scope.selected.push(cat) 
  else 
    $scope.selected.remove(cat) // pretend this function exists in js
}