我在复选框上的每次单击都有四个复选框,启动不同的功能。选中一个复选框,取消选中所有其他复选框。我有以下代码,但问题是我无法在没有先手动删除复选标记然后选择另一个的情况下在支票之间切换。 我的代码:
$scope.checkbox = function(key){
if($scope.checkbox1 === true){
$scope.checkbox2 = false
$scope.checkbox3 = false
$scope.checkbox4 = false
$scope.checkboxValue = 'checkbox one was clicked'
callfunctionOne()
} else if($scope.checkbox2 === true){
$scope.checkbox1 = false
$scope.checkbox3 = false
$scope.checkbox4 = false
$scope.checkboxValue = 'checkbox two was clicked'
callfunctiontwo()
} else if($scope.checkbox3 === true){
$scope.checkbox1 = false
$scope.checkbox2 = false
$scope.checkbox4 = false
$scope.checkboxValue = 'checkbox three was clicked'
callfunctionthree()
} else if($scope.checkbox4 === true){
$scope.checkbox1 = false
$scope.checkbox2 = false
$scope.checkbox3 = false
$scope.checkboxValue = 'checkbox Four was clicked'
callfunctionFour()
}
}
答案 0 :(得分:2)
$scope.checkbox = function(key){
$scope.checkbox1 = false
$scope.checkbox2 = false
$scope.checkbox3 = false
$scope.checkbox4 = false
$scope[key] = true;
$scope.checkboxValue = 'checkbox '+key+' was clicked'
}
你应该考虑使用单选按钮,但是这段代码可以让你做你想做的事。
答案 1 :(得分:1)
您可以将此方法用于您的代码:
对所有复选框使用ng-model
的一个公共变量,
然后使用ng-true-value
来确定选中了哪个复选框
示例:Plunker
<!-- AngularJS Code -->
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.setValues = function(){
$scope.checkbox1 = false;
$scope.checkbox2 = false;
$scope.checkbox3 = false;
$scope.checkbox4 = false;
$scope['checkbox'+tempVariable] = true;
};
});
</script>
<!-- HTML Code -->
<label class="label--checkbox " id="checkbox1">
<input type="checkbox" class="checkbox" ng-model="tempVariable" ng-click="setValues()" ng-true-value="1">
<span class="checkboxLabelText">
Checkbox 1 : {{checkbox1}}
</span>
</label>
<label class="label--checkbox" id="checkbox2">
<input type="checkbox" class="checkbox" ng-model="tempVariable" ng-click="setValues()" ng-true-value="2">
<span class="checkboxLabelText">
Checkbox 2 : {{checkbox2}}
</span>
</label>
<label class="label--checkbox" id="checkbox3">
<input type="checkbox" class="checkbox" ng-model="tempVariable" ng-click="setValues()" ng-true-value="3">
<span class="checkboxLabelText">
Checkbox 3 : {{checkbox3}}
</span>
</label>
<label class="label--checkbox" id="checkbox4">
<input type="checkbox" class="checkbox" ng-model="tempVariable" ng-click="setValues()" ng-true-value="4">
<span class="checkboxLabelText">
Checkbox 4 : {{checkbox4}}
</span>
</label>
答案 2 :(得分:1)
我假设您已获得所需的答案,但这是一个很好的Multi checkbox自定义指令,可处理大多数情况。