Use checkboxes in angularjs to manage array of objects

前端 未结 1 637
长发绾君心
长发绾君心 2021-02-05 22:55

I had asked a question about How to associate objects as models using ng-options in angularjs.

And I got an awesome answer very fast. My followup questions is that the

相关标签:
1条回答
  • 2021-02-05 23:36

    You just need some intermediate value in your scope, and bind checkboxes to it. In your controller - watch for it changes, and manually reconstruct shirt.colors, according to it value.

    <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>
    

    And in your controller:

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

    You can test it here: http://plnkr.co/edit/lh9hTa9wM5fkh3nT09RJ?p=preview

    0 讨论(0)
提交回复
热议问题