如何将嵌套的json对象绑定到复选框

时间:2015-02-15 21:23:56

标签: angularjs

我有一个显示指定公司的用户表。我想使用复选框来编辑它们。我正在使用sessionStorage在表上选择用户时绑定属性。我创造了一个plunker。 Plunker

 <body ng-controller="controller1">
<table class="table table-bordered">
  <thead>
    <tr>
      <th>Company Name</th>
      <th>Name</th>
      <th>UserName</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="user in users" ng-click="selectUser(user)" style="cursor:pointer">
      <td>
        <font ng-repeat="company in user.Companies">{{company.CompanyName}}{{$last?'': ','}} </font>
        </td>
      <td>{{user.Name}}</td>
      <td>{{user.UserName}}</td>
      <td>{{user.Email}}</td>
    </tr>
  </tbody>
</table>

 <div class="form-group">
  <label for="year" class="col-sm-3 control-label">Company(s)</label>
    <div class="col-sm-7">
    <div class="checkbox"><label class="checkbox-inline"> <input type="checkbox" ng-model="user.Companies.CompanyName"> Black Elk </label></div>
    <div class="checkbox"><label class="checkbox-inline"> <input type="checkbox" ng-model="main.check2"> Saratoga </label></div>
    <div class="checkbox"><label class="checkbox-inline"> <input type="checkbox" ng-model="main.check2"> Three Rivers </label></div>
    </div>
 </div>
{{user.Companies[0].CompanyName}}

1 个答案:

答案 0 :(得分:0)

不确定这是最好的方法,但如果你真的想这样做,你可以这样做:

  <div class="col-sm-7">
    <div class="checkbox"><label class="checkbox-inline"> <input type="checkbox" ng-checked="hasCompany(1)" ng-click="changeCompany(1)" ng-model-options="{ getterSetter: true }" > Black Elk </label></div>
    <div class="checkbox"><label class="checkbox-inline"> <input type="checkbox" ng-checked="hasCompany(2)" ng-click="changeCompany(2)" ng-model-options="{ getterSetter: true }" > Saratoga </label></div>
    <div class="checkbox"><label class="checkbox-inline"> <input type="checkbox" ng-checked="hasCompany(3)" ng-click="changeCompany(3)" ng-model-options="{ getterSetter: true }" > Three Rivers </label></div>
    </div>



$scope.hasCompany = function(id){
   return false;// user.Companies contains the id. use underscore or lodash find;
 }
 $scope.changeCompany = function(id){
   return false;//if the company exists in the collection then remove it, else add it
 }

或者,如果你想升级到角度1.3并希望继续使用ng-model,你可以使用ng-model-options

http://plnkr.co/edit/HCwObn5m9RWd7yBOViKS?p=preview