FrontEnd Expert
FrontEnd Expert

Reputation: 5803

How to make one radio button option checked by default angular

I want to make one radio button option should be checked by default. I tried to give ng-model, and ng-init but its not working.

My Html :

<div bindonce ng-repeat="row in results.favorites" style="padding: 0px 10px; white-space: nowrap; border-bottom: 1px solid #efefef; border-top: 1px solid #eee;  border-left: 1px solid #efefef;">
    <input type="radio" ng-click="setFavoriteDashboard(row.id)" ng-model="selectedRow" name="favRadioSel" style="opacity: 1;" class="pointer"/>
    <span bo-text="row.title" style="margin: 10px; position: relative; top: 3px;"></span>
</div>

enter image description here

My JS:

$scope.results = {
  favorites: [{
    id: "WatchList1",
    title: "WatchList1"
  }, {
    id: "WatchList2",
    title: "WatchList2"
  }, {
    id: "WatchList3",
    title: "WatchList3"
  }]
};
$scope.selectedRow = "WatchList1";

Demo : http://plnkr.co/edit/KA9HyQ3bHxJo2Cm9qFm3?p=preview

Upvotes: 1

Views: 158

Answers (3)

Pankaj Parkar
Pankaj Parkar

Reputation: 136134

You need to use $parent to point to parent scope selectedRow variable as ng-repeat does create an child scope, & also you need to use ng-value attribute value without interpolation.

Markup

<input type="radio" 
 ng-model="$parent.selectedRow" 
 ng-value="row.id" name="favRadioSel" 
 style="opacity: 1;" 
 class="pointer" />

Working Plunkr

Upvotes: 0

Jahongir Rahmonov
Jahongir Rahmonov

Reputation: 13723

Set $scope.selectedRow to $scope.results.favorites[0].id and use value instead of ng-value.

How it works: value of the radio button is set to id and ng-model is set to selectedRow, according to your plunker. Thus, if you want to make the first value of the array a default, you just assign selectedRow to its id

See plunker

Upvotes: 0

Joy
Joy

Reputation: 9550

Check working demo: Plunker.

Instead of using ng-value="{{row.id}}", use ng-value="row.id".

Please check documentation of ngValue:

<input
  [ng-value="string"]>
...
</input>

Upvotes: 1

Related Questions