Search code examples
angularjsangular-ngmodel

apply ng-model to groups of multiple choices


In the case of groups of multi-choices, I can build the UI through this simple example:

<div ng-controller="MyCtrl">
<!-- choose colour and size -->
<fieldset ng-repeat="(fieldName, field) in fields">
<label ng-repeat="choice in field">
  <input ng-model="field" type="radio" />
    {{choice}}
</label>
</fieldset>
choices: {{fields}}

and its javascript:

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
  $scope.fields = { /* in practice, the number of fields is dynamic */
  field1: ["red", "blue", "black"], 
  field2: ["big", "small", "medium"]
  }
}

The UI generated allows users to make choices but the {{fields}} ng-model doesn't seem to, as its value doesn't change when user make their choices.

I considered that maybe I need a different variable for ng-model, e.g.

$scope.choices = {field1: "", field2: ""}

To go with $scope.fields to hold user's choices. But various attempt to use a new variable failed. I'm sure the right way to do so has been questioned and answered here. Please kindly bear with my search-fu.


Solution

  • First, your radio buttons don't have a value so you won't be able to bind to anything. Add value="{{choice}}".

    Secondly, you are trying to bind to field which in this case is an array of values like ["red", "blue", "black"] which doesn't make sense. You need to bind to something else.

    You should change your data structure to something like below which has an array we can iterate on for the radio buttons and also a property which we will bind to using ng-model.

    var myApp = angular.module('myApp', []);
    
    myApp.controller("MyCtrl", MyCtrl);
    
    function MyCtrl($scope) {
    
      $scope.fields = { /* in practice, the number of fields is dynamic */
        field1: {
          choices: ["red", "blue", "black"],
          selected: "red"
        },
        field2: {
          choices: ["big", "small", "medium"],
          selected: "big"
        }
      }
    
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
    <div ng-app="myApp" ng-controller="MyCtrl">
      <!-- choose colour and size -->
      <fieldset ng-repeat="(fieldName, field) in fields">
        <label ng-repeat="choice in field.choices">
          <input ng-model="field.selected" type="radio" value="{{choice}}" />{{choice}}
        </label>
      </fieldset>
      <br/>Fields: {{fields}}
    </div>