将复选框绑定到ng-repeat内的对象

时间:2017-08-17 21:46:43

标签: javascript angularjs

我是AngularJS的新手。 我试图绑定这个对象" Optouts.Spouse"我正在从对象计划重复的复选框。

在我的JS中我有:

$scope.optouts = { spouse: {}, children: {} };
$scope.plans = {mec:true;anotherone:true};

在我的Html中我有:

<span ng-repeat="(plan,x) in plans">{{plan}}
   <input type="checkbox" ng-model="optouts.spouse.plan"
          ng-checked="!optouts.spouse.plan"> 
</span>

但它没有绑定到对象。我究竟做错了什么?我怎样才能做到这一点?感谢!!!

真的没有什么可以展示......

 their.plans = {};
 their.toggles = {};
 their.optouts = { spouse: {}, children: {} };
 their.optouts = { spouse: {'mec':true}, children: {} };
 their.spouse = { has:true,
                  firstName: 'Mary',
                  lastName:'Doe',
                  birthDate:'8/10/1989',
                  gender:'Female' }
 their.plans = { mec:true, mr1: true, anotherone:true }

1 个答案:

答案 0 :(得分:1)

既然你在重复计划,我想你正在努力实现这个目标:

<span ng-repeat="(plan,x) in plans">{{plan}}
   <input type="checkbox" ng-model="optouts.spouse.plans[plan]"> 
</span>

您在optouts.spouse.plan上创建了一个属性,但您想要的是在计划下“映射”真/假值。也就是说,通过使用bracket notation和计划的当前值,您可以实现此目的。

默认情况下,所有计划最初都会取消选中,因为它们没有值。该复选框将直观地表示true或false,因此不需要使用ng-checked。如果复选框至少切换一次,则给定计划将具有真/假值。

如果您需要将它们设置为true,最好的办法是在控制器中迭代它们,并使用值 true 初始化它们。

相关问题