我有一个复选框列表,我希望用户只能选择其中两个,我想获得所选的值。 我试过这段代码 的 HTML
<input type="checkbox" value={{item.name}} id={{item.name}} ng-click="toggleSelection(item.name)">
JS
$scope.toggleSelection = function toggleSelection(id) {
if(typeof $scope.firstSelectedService === 'undefined'){
$scope.firstSelectedService=id;
}
else
if(typeof $scope.secondSelectedService === 'undefined'){
$scope.secondSelectedService=id;
}
else
if($scope.firstSelectedService === id){
window.alert("test11");
$scope.firstSelectedService='';
}
else
if($scope.secondSelectedService === id){
window.alert("test2");
$scope.secondSelectedService='';
}
};
如果用户选择第三个,我想删除secondSelectedService的旧值,如果他取消选中已选中的值,我想删除它的值。取消选择一个时我遇到了麻烦,我没有看到#34; test1&#34;或者&#34; test2&#34;,只有当我再次选中复选框时才能看到它。我只想问一下这样做的好方法吗?它看起来并不干净。
答案 0 :(得分:1)
您的where
指令不应包含ng-click
插值指令,{{}}
上也应该ng-model
,以便更新项的值,不需要致电checkbox
<强>标记强>
toggleSelection
然后,如果您想要选择多少项,那么您可以使用<div ng-repeat="item in items">
<input type="checkbox" ng-value="item.value" id="{{item.name}}"
ng-click="item.selected!=item.selected" ng-model="item.selected"/>
</div>
filter
,这将为您提供在html上选择的项目
<强>标记强>
{{(items|filter: {selected: true}: true)}}
或强>
如果你想在控制器中使用那些选定的元素,那么你可以在控制器中使用<body class="container" ng-app="firstApp" ng-controller="EmpController">
<div ng-repeat="item in items">
<input type="checkbox" ng-value="item.value" id="{{item.name}}"
ng-click="item.selected!=item.selected" ng-model="item.selected" />
{{item.name}}
</div>
{{items|filter:{selected: true}: true}}
</body>
对象,比如$filter
答案 1 :(得分:1)
$scope.variables = [];
$scope.toggleSelection = function toggleSelection(id) {
if($scope.variables.length >= 2){
$scope.variables[0] = $scope.variables[1];
$scope.variables[1] = id;
} else {
$scope.variables.push(id);
}
}