是否有更优雅的方式将复选框变成单选按钮?

时间:2017-05-31 07:42:56

标签: javascript

尝试将我的复选框变成单选按钮。这很好用

ng-change="second=false;third = false;fourth = false;"

这是掠夺者

http://plnkr.co/edit/yTJUZcFoLsSEBjruRuEY?p=preview

有没有办法让数组中的每个元素都为假除了模型?

示例

ng-model=myArray[3]

所以myArray[0], myArray[1], myArray[... n]都是假的 EXCEPT myArray[3],这是真的。

2 个答案:

答案 0 :(得分:2)

这应该相当优雅:PLNKR

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.radio = new Array(4).fill(false)
  $scope.changed = function(el){
    $scope.radio = $scope.radio.map((v,i)=>i==el)
  }
});

和html:

<div>{{radio[0]}}|{{radio[1]}}|{{radio[2]}}|{{radio[3]}}
  <br/>
  <input ng-repeat="r in radio track by $index" type="checkbox" ng-model="radio[$index]" ng-change="changed($index)"  />

答案 1 :(得分:1)

好吧,我尝试根据您的要求创建更改。看看这对你有用。

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.checkbox = [false,false,false,false];

  $scope.changeStatus = function(index){
    //fill in not supported in IE and opera
    $scope.checkbox.fill(false);
    //Uncomment and Use this in IE and Opera in case fill throw error
    //for(let i = 0 ; i < $scope.checkbox.length; ++i){
    //    $scope.checkbox[i] = false;
    //}

    if($scope.checkbox[index])
      $scope.checkbox[index] = false;
    else
      $scope.checkbox[index] = true;

    console.log($scope.checkbox);  
  }
});

您的HTML代码将是

<body ng-controller="MainCtrl">
  <div>
  <br/>
  <input type="checkbox" ng-model="checkbox[0]" ng-click='changeStatus(0)' />
  <input type="checkbox" ng-model="checkbox[1]" ng-click='changeStatus(1)'/>
  <input type="checkbox" ng-model="checkbox[2]" ng-click='changeStatus(2)' />
  <input type="checkbox" ng-model="checkbox[3]" ng-click='changeStatus(3)' />
  </div>
</body>
相关问题