【问题标题】:Angular js checkbox to count checked checkbox's using $watchAngularjs 复选框使用 $watch 计算选中的复选框
【发布时间】:2023-03-09 13:54:01
【问题描述】:

我想在任何时间点从列表中检查任何 3 个复选框,当所选复选框的长度等于 3 时,我想禁用所有剩余的复选框(未选中的复选框)。但是选中的复选框应该处于启用状态。如果可能,我想使用 $watch 来实现这一点。(在任何时候用户只能选择 3 个复选框;)
这是我的html代码-

<html>
<head>
  <script type="text/javascript" src="angular.js"></script>
  <script type="text/javascript" src="app.js"></script>
</head>
<body ng-app="myApp">
    <div ng-controller="myCtrl">
      <div ng-repeat="std in students">
        {{std.name}}<input type="checkbox" ng-model="std.selected" ng-checked="" ng-disabled=""/>
      </div>
    </div>
</body>
</html>

这是我的 app.js

var app=angular.module("myApp",[]);
app.controller("myCtrl",function($scope){
$scope.students=[
  {selected:"f", name:"peter"},
  {selected:"f", name:"santa"},
  {selected:"f",name:"rita"},
  {selected:"f", name:"shona"},
  {selected:"f", name:"mickey"},
  {selected:"f",name:"nicky"}
]
});

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-ng-repeat


    【解决方案1】:

    控制器代码:

        $scope.students=[
          {selected:false, name:"peter"},
          {selected:false, name:"santa"},
          {selected:false, name:"rita"},
          {selected:false, name:"shona"},
          {selected:false, name:"mickey"},
          {selected:false, name:"nicky"}
        ];
        $scope.disabledCheckboxes = false;
        $scope.checked = function() {
            $scope.disabledCheckboxes = $scope.students.filter(function(ch) {
                return ch.selected;
            }).length > 3;
        };
    

    和html:

        <div ng-repeat="std in students">
           {{std.name}}
           <input type="checkbox" ng-model="std.selected" ng-change="checked()"
                  ng-disabled="disabledCheckboxes && !std.selected"/>
        </div>
    

    使用&amp;&amp; !std.selected,您将能够取消选中选中的复选框。

    【讨论】:

    • 您可以使用手表实现相同的目的。但我想说这更清楚。
    • 我需要这个使用手表,因为我的 selected_students 列表与学生不同。在我的 selected_students 列表中,随时都会选择 3 名学生,其中学生 std.selected 在数据库中默认为 false。我不能使用 !std.selected 因为从数据库中获取总是错误的,我从 selected_students 的学生中推送了 3 个学生,其中选择的值发生了变化。
    • 我将解释我的代码中发生了什么。当用户从学生列表中检查一个学生时,我将该学生推送到 selected_students 列表中,该列表是临时数组。现在 selected_students 中的选定字段不断变化,但在学生数组中,我默认存储为 false。所以不能使用 !std.selected 因为它总是错误的。我如何使用 selected_students 列表?如果我使用该列表,那么它只检查 3 条记录,因为它的长度在任何时候都是 3。请帮助@jcubic
    • @Sudarshan 更简单,您无需使用 selected true 过滤原始列表来计算所选用户,而只需使用 $scope.checked = function() { $scope.disabledCheckboxes = $scope.selected_students.length &gt; 3; }
    • 谢谢@jcubic 我刚刚从我的数据库中删除了始终为假的默认值,并使用 std.selected 创建了临时模型。我没有使用 ng 禁用检查。在 $watch 我检查了 std.selected==t && len===3 然后禁用所有剩余的检查。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-06-10
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多