11

angularjs で ng-options を使用してオブジェクトをモデルとして関連付ける方法について質問 しました。

そして、私は素晴らしい答えを非常に早く得ました。私のフォローアップの質問は、応答が<select mutiple>子オブジェクト配列を処理するために使用することです。

http://plnkr.co/edit/FQQxrSE89iY1BnfumK0A?p=preview<select>で、私が欲しいものの実際の例を見ることができます。

オブジェクト配列からアイテムを繰り返しながら、そのオブジェクト配列を処理するため<input type='checkbox'>に(の代わりに)どのように使用できますか。<select>ng:model="shirt.colors"colors

これが非常に複雑に見える理由は、値の配列ではなくオブジェクトの配列を管理する必要があるためです...たとえば、フィドルを見ると、複数の色を持つcolorオブジェクトとオブジェクトがあります。shirt

オブジェクトが変更された場合、オブジェクト内の対応するオブジェクトcolorを変更する必要があります。colorshirt

前もって感謝します。

4

1 に答える 1

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>

そしてあなたのコントローラーで:

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

ここでテストできます: http://plnkr.co/edit/lh9hTa9wM5fkh3nT09RJ?p=preview

于 2013-02-09T07:41:53.797 に答える