feus4177
feus4177

Reputation: 1383

Angular: Correctly show which radio is selected initially

I have the following Plunker: http://plnkr.co/edit/5mfYvsko2cW1SS66CqJC?p=preview. When it loads initially selected will have a value of [true] but the corresponding radio will not be selected. If I uncomment out the following line:

$scope.selected = $scope.items[1].value;

then the correct radio will be shown. I get that this is a result of how Javascript handles equality comparisons with arrays. Unfortunately in my actual situation, I can't see any reasonable way to ensure that I am assigning the same object. Are there any other ways I could get the correct radio to show up as selected on the initial load?

Upvotes: 1

Views: 51

Answers (2)

feus4177
feus4177

Reputation: 1383

Well there isn't any perfect solution but here is what I went with:

$scope.selected = {value: [true], name: 'True'};
$timeout(function () {
  $('input[type="radio"]').each(function () {
    if ($scope.selected.value.toString() === this.value) {
      this.checked = true;
    }
  });
});

I also found this answer which would be a good alternative in most cases. The plunker it references doesn't have to have the $scope.selectedOption.value as a string like it does to start with.

Upvotes: 0

Sabarish
Sabarish

Reputation: 531

Please find the answer updated in plunker

Have modified the scope

  $scope.items = [
    {value: 'false', name: 'False'},
    {value: 'true', name: 'True'},
    {value: 'neither', name: 'False or true'}
  ];

and html

  <label ng-repeat="item in items" ng-init="selected='true'">
    <input type="radio" ng-model="selected" ng-value="item.value" >
    {{ item.name }}
  </label>

Upvotes: 1

Related Questions