angular.js - angular radio repeat 預設選取值
巴扎黑
巴扎黑 2017-05-15 16:59:56
0
2
630

html程式碼如下:

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

js程式碼如下:

$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"};

目前我這樣做,不能預設選取一個值,也不知道問題出在哪裡。

我想頁面一載入就預設選取一個值,其中每一項的值類型是對象,我該如何做?

巴扎黑
巴扎黑

全部回覆(2)
漂亮男人

需要設定ng-model的預設值
如:

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

將會預設選擇這一項。

不能使用

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

因為ng-model中對於Object只有相同的引用才會認為兩者相等,上述做法新建一個對象,與repeat中的value不等

某草草

可在 ng-repeat 中使用 ng-checked , 舉個栗子:

<label ng-repeat="(key, val) in genders track by $index">
    <input type="radio" name="gender" value="{{key}}" ng-checked="list.gender==key">{{val}}
</label>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板