只选择两个复选框

时间:2015-06-26 18:44:18

标签: javascript html angularjs checkbox angularjs-ng-repeat

我有一个复选框列表,我希望用户只能选择其中两个,我想获得所选的值。 我试过这段代码 的 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;,只有当我再次选中复选框时才能看到它。我只想问一下这样做的好方法吗?它看起来并不干净。

2 个答案:

答案 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)}}

Plunkr Demo

如果你想在控制器中使用那些选定的元素,那么你可以在控制器中使用<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);
    }
}