AngularJs:如何设置基于模型的单选button
我有一个模型返回storeLocations对象与isDefault值。 如果isDefault返回true,我不想在组中设置该单选button。
不知道是否需要做每个$(数据,函数(索引,值),并遍历每个返回的对象,或者如果有一个更容易的方法来做到这一点使用angular度的结构。
目的:
storeLocations = [ { ... more values, isDefault: true } ] 标记:
  <tr ng-repeat="location in merchant.storeLocations"> <td>{{location.name}}</td> <td>{{location.address.address1}}</td> <td>{{location.address.address2}}</td> <td>{{location.address.city}}</td> <td>{{location.address.stateProvince}}</td> <td>{{location.address.postalCode}}</td> <td>{{location.address.country}}</td> <td>{{location.website}}</td> <td>{{location.zone}}</td> <td><input type="radio" ng-model="location.isDefault" value="{{location.isDefault}}" name="isDefault_group"></td> 
	
 使用ng-value而不是value 。 
 ng-value="true" 
 由于代码重复,使用ng-checked版本更糟糕。 
 如果您有一组单选button,并且想要设置基于模型的单选button,则会自动检查具有相同value和ng-model单选button。 
 <input type="radio" value="1" ng-model="myRating" name="rating" class="radio"> <input type="radio" value="2" ng-model="myRating" name="rating" class="radio"> <input type="radio" value="3" ng-model="myRating" name="rating" class="radio"> <input type="radio" value="4" ng-model="myRating" name="rating" class="radio"> 
 如果myRating的值是“2”,则select第二个单选button。 
 结束使用内置的angular度属性ng-checked="model" 
 在所有模型中,我看到更强大并避免出现isDefault的一种方法是使用ng-attributes ng-model , ng-value和ng-checked 。 
ng-model :将值绑定到您的模型。
  ng-value :传递给ng-model绑定的值。 
ng-checked :被评估的值或expression式。 有用的无线电button和checkbox。
使用示例:在下面的示例中,我有我的模型和我的站点支持的语言列表。 为了显示支持的不同语言并用select的语言更新模型,我们可以这样做。
 <!-- Radio --> <div ng-repeat="language in languages"> <div> <label> <input ng-model="site.lang" ng-value="language" ng-checked="(site.lang == language)" name="localizationOptions" type="radio"> <span> {{language}} </span> </label> </div> </div> <!-- end of Radio --> 
 只要评估expression式(site.lang == language)为true,我们的模型site.lang就会得到一个language值。 这将允许您轻松地与服务器同步,因为您的模型已经有了变化。 
正如在问题评论中所讨论的那样,这是你可以做到的一个方法:
- 首次检索数据时,循环遍历所有位置,并将storeDefault设置为当前默认的商店。
-  在标记中: <input ... ng-model="$parent.storeDefault" value="{{location.id}}">
- 在保存数据之前,循环遍历所有的merchant.storeLocations,并将isDefault设置为false,除了location.id比较等于storeDefault的商店。
上面假设每个位置都有一个字段(例如,id),它保存着一个唯一的值。
请注意,使用$ parent.storeDefault是因为ng-repeat创build了一个子作用域,我们想要在父作用域上操作storeDefault参数。
小提琴 。