使用angularjs中的复选框来管理对象数组

Gun*_*run 11 angularjs

我问了一个关于如何使用angularjs中的ng-options将对象关联为模型的问题 .

而且我得到了一个非常快的答案.我的后续问题是响应用于<select mutiple>处理子对象数组.

您可以<select>http://plnkr.co/edit/FQQxrSE89iY1BnfumK0A?p=preview上查看我想要的工作示例.

我如何使用<input type='checkbox'>(而不是<select>)处理该对象数组,即ng:model="shirt.colors"在重复colors对象数组中的项目时.

原因,这对我来说似乎很复杂,我必须管理一个对象数组而不是数组数组...例如,如果你看小提琴,有color对象和shirt对象有多种颜色.

如果color对象发生更改,则应更改color对象中的相应shirt对象.

先感谢您.

Pyt*_*nic 18

您只需要在范围中使用一些中间值,并将复选框绑定到它.在你的控制器中 - 注意它的变化,并根据它的值手动重建shirt.colors.

<div ng-repeat='shirt in shirts'>
  <h3>Shirt.</h3>
  <label>Size: <input ng-model='shirt.size'></label><br/>
  <label>Colors:</label>
  <label ng-repeat="color in colors">
    {{color.label}} <input ng-model="selection[$parent.$index][$index]" type="checkbox"/>
  </label>

    </label>
</div>
Run Code Online (Sandbox Code Playgroud)

在你的控制器中:

$scope.selection = [[],[]];
$scope.$watch('selection', function () {
  console.log('change', $scope.selection);
  angular.forEach($scope.selection, function (shirtSelection, index) {
    $scope.shirts[index].colors = [];
    angular.forEach(shirtSelection, function (value, index2) {
      if (value) $scope.shirts[index].colors.push($scope.colors[index2]);
    });
  });
}, true);
Run Code Online (Sandbox Code Playgroud)

你可以在这里测试一下:http://plnkr.co/edit/lh9hTa9wM5fkh3nT09RJ?p = preview