ng-重复循环复选框

ng-repeat loop on checkboxes

本文关键字:复选框 循环 ng-      更新时间:2023-09-26
  <span  ng-repeat="s  in colors">
         <p><li><input type="checkbox"   ng-model="colors[id].checked"   ng-change="setColor(s.id)"> &nbsp; {{s.name}}</li></p> 
</span> 

在我的控制器中,

$scope.colorsel= []; 
    $scope.setColor = function(a){
         if($scope.colorsel.indexOf(a) == -1 ){
              $scope.colorsel.push(a);
         }
         else{
             var index =  $scope.colorsel.indexOf(a)
            $scope.colorsel.splice(index,1);
         }
    }

我正确获取了颜色值。但是如果我选择一个复选框,它只是显示所有复选框都被选中(意味着勾号出现在所有复选框中,但它只接受在 colorel 数组中选择的复选框的 id(。如果我选择另一个,所有的刻度线都会消失。请帮我解决这个问题。

只需直接引用对象:ng-model="s.checked"

这:colors[id].checked是错误的,因为你引用了相同的id(也许 s.id colors[s.id].checked是你正在尝试的(。因此,如果您的控制器中有$scope.id = 2,那么您总是引用colors[2].checked

试试这个

<span  ng-repeat="s in colors">
 <p>
  <input type="checkbox" ng-model="s[id].checked" ng-change="setColor(s.id)"> &nbsp; {{s.name}}
 </p> 
</span> 
ng-repeat="s in colors"

foreach(s in colors)相似因此,如果要从颜色访问值,则需要使用"S"代替颜色。