search

Home  >  Q&A  >  body text

angular.js - angular radio repeat default selected value

The html code is as follows:

<ul>
  <li ng-repeat="thing in favoriteThings">
    <input type="radio" ng-value="thing" ng-model="selected" name="stuff"/>
      {{thing.text}}
  </li>
</ul>

js code is as follows:

$scope.favoriteThings = [
    {nr: 1, text: "Raindrops on roses"},
    {nr: 2, text: "Whiskers on kittens"},
    {nr: 3, text: "Bright copper kettles"},
    {nr: 4, text: "Warm woolen mittens"},
    {nr: 5, text: "Brown paper packages tied up with strings"},
    {nr: 6, text: "Cream colored ponies"},
    {nr: 7, text: "Crisp apple streudels"},
    {nr: 8, text: "Doorbells"},
    {nr: 9, text: "Sleigh bells"},
    {nr: 10, text: "Schnitzel with noodles"},
    {nr: 11, text: "Wild geese that fly with the moon on their wings"},
    {nr: 12, text: "Girls in white dresses with blue satin sashes"},
    {nr: 13, text: "Snowflakes that stay on my nose and eyelashes"},
    {nr: 14, text: "Silver white winters that melt into springs"}
  ];
  
  $scope.selected = {nr: 1, text: "Raindrops on roses"};

Currently when I do this, I can't select a value by default, and I don't know where the problem lies.

I want a value to be selected by default as soon as the page is loaded, and the value type of each item is an object. How should I do this?

巴扎黑巴扎黑2865 days ago648

reply all(2)I'll reply

  • 漂亮男人

    漂亮男人2017-05-15 17:01:56

    You need to set the default value of ng-model
    such as:

      $scope.selected = $scope.favoriteThings[0];

    This option will be selected by default.

    Cannot be used

      $scope.selected = {nr: 1, text: "Raindrops on roses"};

    Because only the same reference to Object in ng-model will be considered equal. The above method creates a new object, which is not equal to the value in repeat

    reply
    0
  • 某草草

    某草草2017-05-15 17:01:56

    Can be found in ng-repeat 中使用 ng-checked , for example:

    <label ng-repeat="(key, val) in genders track by $index">
        <input type="radio" name="gender" value="{{key}}" ng-checked="list.gender==key">{{val}}
    </label>

    reply
    0
  • Cancelreply