无法在Angular.js中使用ng-repeat设置默认选中的单选按钮选项

时间:2016-08-14 20:55:22

标签: javascript angularjs

这是我的代码:

    <label ng-repeat="option in product.DeliveryOptions" class="radio-inline product__filtr__form__label__input">
  <input type="radio" ng-model="product.SelectedDeliveryOption" ng-change="changeDeliveryType(product)" name="inlineRadioOptions{{product.ID}}"
class="product__filtr__form__radio" value="{{option.Method}}">{{option.Description}}
</label>

这是嵌套的ng-repeat块。父块是product in products。如您所见,每个产品都有SelectedDeliveryOption。例如,我有两个单选按钮。第一个值为option.Method) - "bronze",第二个为"silver"。此值(ng-model="product.SelectedDeliveryOption")为"silver"。但默认情况下不会选择单选按钮。我试过了ng-checked = "option.Method == product.SelectedDeliveryOption",但对我不起作用。

 $scope.initProductsTable = function (products) {
            $scope.products = products;    }

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

确保value对象option.Method位于:

<input type="radio" ng-model="product.SelectedDeliveryOption" ng-change="changeDeliveryType(product)" name="inlineRadioOptions{{product.ID}}"
class="product__filtr__form__radio" value="{{option.Method}}">

的格式为:

option.Method = {"id": "12345",
            "value": "teste"}

并使用ng-value指令;

如下面的示例:

使用radio button时,您必须使model值与value中的radio button相等:

检查下面的代码段:

(function(angular) {
  'use strict';
  angular.module('includeExample', ['ngAnimate'])
    .controller('ExampleController', ['$scope', '$q',
      function($scope, $q) {
       $scope.color = {
        name: 'blue'
      };
      $scope.specialValue = {
        "id": "12345",
        "value": "green"
      };        


      }
    ]);
})(window.angular);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.1/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.1/angular-animate.js"></script>

<body ng-app="includeExample">
  <div ng-controller="ExampleController">
    <form novalidate class="simple-form">
    <label>
    <input type="radio" ng-model="color.name" value="red">
    Red
  </label><br/>
  <label>
    <input type="radio" ng-model="color.name" ng-value="specialValue">
    Green
  </label><br/>
  <label>
    <input type="radio" ng-model="color.name" value="blue">
    Blue
  </label><br/>
  <tt>color = {{color.name | json}}</tt><br/>
  </form> 

  </div>
</body>