角度复选框不会保持选中状态

Angular checkboxes wont remain checked?

本文关键字:状态 复选框      更新时间:2023-09-26

我有一些angular.js代码,当用户单击某些复选框时,它会填充数组。我生成了一个带有"ng repeat"的复选框列表,当用户提交表单时,我需要将一个数组保存到服务器端。。小提琴在这里。。但是,复选框不会保持"选中"状态?有人对如何修复这个UI错误有什么建议吗?

html

  <div ng-controller="MyCtrl">
      <div class="col-sm-6">
          <div class="form-group">
              <label>Search by Organism :</label>
              <input type="text" class="form-control" placeholder="Organism" ng-model="filterText">
          </div>
          <div class="well" style="max-height: 250px; overflow: auto;">
              <ul class="list-group checked-list-box" ng-repeat="x in organisms | filter: filterText">
                  <label>
                      <input type="checkbox" ng-change="match($index)" ng-model="orgs[$index]"> {{ x }}
                  </label>
              </ul>
          </div>
      </div>
    </div>

角度

 var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
    $scope.orgs = [];
        $scope.match = function(index) {
            console.log("index", index);
            console.log("organism: ", $scope.organisms[index]);
            $scope.orgs[index] = $scope.organisms[index];
        };
        $scope.organisms = ["Pseudomonas aeruginosa", "Stenotrophomonas maltophilia", "Pseudomonas luteola", "Pseudomonas aeruginosa", "Streptococcus pneumoniae", "Candida tropicalis", "IAV-H1N1", "IAV-H1N2", "IAV-H3N2", "IAV-mixed", "IAV-H10N8", "IAV-H2N2", "IAV-H5N1", "IAV-H5N6", "IAV-H7N3", "IAV-H7N7", "IAV-H7N9", "IAV-H9N2"];

}

注释行

$scope.orgs[index] = $scope.organisms[index]

这将防止数组被覆盖。


改进

我已经更新了小提琴。您不能单击复选框并将值保存在另一个数组中。最好的方法是使用Array原型push。下面是您的新匹配函数。

$scope.match = function(orgName) {
    var index= $scope.selection.indexOf(orgName);
    if (index> -1) {
        $scope.selection.splice(index, 1);
    }
    else {
        $scope.selection.push(orgName);
    }
};

此外,复选框还有一个名为value的属性。这可以用作数据的占位符。

更新的fiddle

如果这是你想要的,请将答案标记为已接受。