Alex Gurskiy
Alex Gurskiy

Reputation: 376

Can't set default selected radio button's option using ng-repeat in Angular.js

This is my code:

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

This is nested ng-repeat block. Parent block is product in products. As you can see each product has SelectedDeliveryOption. For example I have two radio buttons. Values(option.Method) - "bronze" for the first and "silver" for the second. This value (ng-model="product.SelectedDeliveryOption") is "silver". But radio button isn't selected by default. I've tryed: ng-checked = "option.Method == product.SelectedDeliveryOption", but doesn't work for me.

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

Could anyone help me?

Upvotes: 2

Views: 1133

Answers (1)

Alvaro Silvino
Alvaro Silvino

Reputation: 9763

Make sure if the value object option.Method in:

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

has the format:

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

and use ng-value directive;

like the example bellow:

When using radio button you have to make equal the model value and the value from the radio button:

check the snippet bellow:

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

Upvotes: 1

Related Questions