复选框上的ng-repeat循环

时间:2016-05-06 16:33:18

标签: javascript jquery angularjs checkbox

  <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);

         }
    }

正确获取colorsel值。但是如果我选择一个复选框,它只是显示所有复选框都被选中(表示所有复选框中都出现勾选标记,但它只取得在colorsel数组中选中的复选框的ID)。如果我选择其他一个,所有刻度线都会消失。 Plz帮我解决了这个问题。

3 个答案:

答案 0 :(得分:1)

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

这个:colors[id].checked是错误的,因为你引用了相同的 id (或许 s.id colors[s.id].checked就是你的意思试)。因此,如果您的控制器$scope.id = 2中存在的数量超过您始终引用colors[2].checked的数量。

答案 1 :(得分:0)

试试这个

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

答案 2 :(得分:0)

ng-repeat="s in colors"foreach(s in colors)类似 因此,如果要从颜色中访问值,则需要使用“S”代替颜色。

相关问题