在特定条件下使用单选按钮切换ng-repeat

时间:2018-01-13 07:23:37

标签: javascript angularjs

我有一些由ng-repeat生成的单选按钮切换。默认情况下,我希望第一个单选按钮全部切换,如果条件适用,我只想切换单选按钮。

<li ng-repeat="method in itemGroup.ShippingMethods">
    <input ng-model="itemGroup.SelectedShippingMethod" 
           ng-change="changeShipping(itemGroupKey, 
           itemGroup.SelectedShippingMethod)" 
           type="radio" 
           name="Shipping" 
           id="method.Name" 
           value="method.Name" 
    />

在我的JS文件中:

$scope.itemGroup = { SelectedShippingMethod: "Express" };

代码的意图是默认切换第一个按钮,除非条件被触发(快速发送),其中该按钮将被切换。

在[标准,快速,快速]列表中,将切换标准单选按钮。在[标准,快速,快速]列表中,将切换快速单选按钮。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

你可以在收音机输入上使用这样的东西:

ng-checked="$first || item == 'Express'"

注意:根据您的数据结构和循环,item == 'Express'会有所不同。


以下是此解决方案的简单演示:

angular.module('myApp', [])
.controller('myCtrl', function($scope) {
  $scope.itemslists = {
    list1: ['Standard', 'Fast', 'Speedy'],
    list2: ['Standard', 'Express', 'Speedy'],
    list3: ['Standard', 'Fast', 'Express']
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
  <ul style="list-style-type: none" ng-repeat="(list, items) in itemslists">
    <h3 style="margin-bottom: 2px">{{list}}</h3>
    <li ng-repeat="item in items">
      <label>
        <input type="radio" name="{{list}}" ng-checked="$first || item == 'Express'"/>
        {{item}}
      </label>
    </li>
  </ul>
</body>

相关问题