简体   繁体   中英

AngularJS: Radio buttons in ng-repeat

I've got a set of radio buttons in a ng-repeat , following what I found in this answer . I just can't figure out how to add an ng-model to it.

   <tr ng-repeat="service in selectservice.services track by $index">
          <td>
            <input type="radio" name="serviceSelections" ng-value="{{service.name}}" id="service{{service.name}}">
          </td>
          <td>
            <h3>
              {{service.name}}
            </h3>
            <p>{{service.caption}}</p>
          </td>
        </tr>

With this controller:

(function() {
  'use strict';

  angular.module('pb.ds.selectservice').controller('SelectServiceController', function($log) {
    var _this = this;

    _this.selectedService = 0;

    _this.services = [
      {
        selected: false,
        name: 'Postmates',
        caption: 'Guaranteed delivery within time'
      },
      {
        selected: true,
        name: 'Deliv',
        caption: 'Guaranteed delivery within time',
      },
      {
        selected: false,
        name: 'Roadie',
        caption: 'Guaranteed delivery within time',
      }
    ];
  });
})();

and, in my route, for this view:

        content: {
          controller: 'SelectServiceController as selectservice',
          templateUrl: 'modules/select-service/templates/select-service.html'
        },

The radio group correctly shows the second radio selected. But how do I update the model? What, exactly is the model? I have tried ng-model="selectservice.selectedService" which should be 0 , but then no radio is selected.

You need to have a model in your controller to assign the radio button group an ng-model. In your case it should be

    _this.selectedService = "";

Since it appears that you want to get the selected service's name.

Setting your HTML like below will make it work.

<tr ng-repeat="service in selectservice.services track by $index">
          <td>
            <input type="radio" ng-model="selectservice.selectedService" value="{{service.name}}" id="service{{service.name}}">
          </td>
          <td>
              {{service.name}}
            <p>{{service.caption}}</p>
          </td>
      </tr>

After this whatever button you check, your _this.selectedService will update with the corresponding button's name. So if you select the "Deliv" radio button, your _this.selectedService will get the value "Deliv". I hope found your answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM