切换ng-repeat angularjs中的开关

时间:2017-09-21 06:59:45

标签: javascript angularjs

如何在ng-repeat中一次只有一个切换开关?

是否可以使用$index

我正在使用ng-repeat显示我的数据的切换开关,我希望一次只打开一个开关。如果我打开一个,其他人应该关闭。

<div class="contacts" ng-repeat="data in dataList">
 <md-switch ng-model="data" >
    Switch {{ data }}
  </md-switch>
</div>

1 个答案:

答案 0 :(得分:0)

&#13;
&#13;
<html lang="en">

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css">
</head>

<body ng-app="myApp" ng-cloak ng-controller="Ctrl">
  <div ng-repeat="data in toggleModel">
  <md-switch ng-model="data.isToggle" aria-label="Switch 2" class="md-warn" ng-change="changeToggle(data,data.isToggle)">
    Switch 
  </md-switch>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.11/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.11/angular-animate.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.11/angular-aria.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.js"></script>

  <script type="text/javascript">
    var app=angular.module('myApp', ['ngMaterial']);
    app.controller("Ctrl",["$scope",function($scope){
    $scope.toggleModel=[
    {
    isToggle:false
    },{
    isToggle:false
    },{
    isToggle:false
    },{
    isToggle:false
    },{
    isToggle:false
    },{
    isToggle:true
    }];
    $scope.changeToggle=function(data,isToggle){
      angular.forEach($scope.toggleModel,function(toggle){
        toggle.isToggle=false;
      });
      data.isToggle=isToggle;
    }
    }]);
  </script>
</body>

</html>
&#13;
&#13;
&#13;