Rafff
Rafff

Reputation: 1518

How to check radio based on model custom value

I'm trying to use the example code from this Angularjs example page in my app for input[radio]. I choose to use an object as a value of a particular radio button, so each of the radio buttons in a group has a value of some object.

In the plunkr example, if you set the model to green which is:

$scope.color = {
  name: 'green'
};

The proper radio button is not checked by default. I think its because the value of this radio button is an object.

Any ideas how to make it work? How do I check the proper radio button if its value is an object?

Upvotes: 0

Views: 520

Answers (2)

Malathy Venkatesan
Malathy Venkatesan

Reputation: 213

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-radio-input-directive-production</title>
  

  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
  

  
</head>
<body ng-app="radioExample">
  <script>
  angular.module('radioExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.specialValue = {
        "id": "12345",
        "value": "green"
      };
      $scope.color = {
        name: $scope.specialValue
      };
    }]);
</script>
<form name="myForm" ng-controller="ExampleController">
  <label>
    <input type="radio" ng-model="color.name" value="red">
    Red
  </label><br/>
  <label>
    <input type="radio" ng-model="color.name" ng-value="specialValue" checked=checked>
    Green
  </label><br/>
  <label>
    <input type="radio" ng-model="color.name" value="blue">
    Blue
  </label><br/>
  <tt>color = {{color.name | json}}</tt><br/>
 </form>
 Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
</body>
</html>

<!-- 
Copyright 2017 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->

Upvotes: 0

Alon Eitan
Alon Eitan

Reputation: 12025

You need to reference the model $scope.color.name to the "green" object which is defined in the ngValue directive:

$scope.specialValue = {
  id: '12345',
  value: 'green'
};

$scope.color = {
  name: $scope.specialValue
};

Because it's ngValue directive is bound to specialValue

<label>
  <input type="radio" ng-model="color.name" ng-value="specialValue">
  Green
</label>

Here is a working example.

Upvotes: 0

Related Questions