javascript 从 AngularJS 中的多个复选框中获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30421266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:09:08  来源:igfitidea点击:

Get value from multiple checkboxes in AngularJS

javascripthtmlangularjsangularjs-scope

提问by Tech Solvr

Following is my code in which I am trying to get values of multiple checkboxes selected, but some how its not working. Let me know what I am doing wrong here, BTW the list is dynamic and not going to contain only 3 items in an array.

以下是我的代码,我试图在其中选择多个复选框的值,但有些是如何不起作用的。让我知道我在这里做错了什么,顺便说一句,列表是动态的,并且不会只包含数组中的 3 个项目。

My Plnkr - PLNKR CODE

我的 Plnkr - PLNKR 代码

HTML -

HTML -

    <table>
    <tr ng-repeat="student in studentList">
   <td ng-bind="$index + 1"></td>
   <td ng-bind="student.email"></td>
   <td ng-bind="student.fname"></td>
   <td ng-bind="student.lname"></td>
   <td>
    <input type="checkbox" ng-model="studcheck" ng-value="$index" />
   </td>
</tr>
</table>
{{studcheck}}

CONTROLLER CODE -

控制器代码 -

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

myApp.controller('mainCtrl', function($scope){
  $scope.studentList = [
    {email: '[email protected]', fname: 'Test1', lname: 'Last1' },
    {email: '[email protected]', fname: 'Test2', lname: 'Last2' },
    {email: '[email protected]', fname: 'Test3', lname: 'Last3' },
  ];

  $scope.studcheck = {};
});

回答by Daniel Perez

You cannot use ng-modelmultiple times on the same model, but here just specify the key and it should be fine:

你不能ng-model在同一个模型上多次使用,但这里只指定键就可以了:

<input type="checkbox" ng-model="studcheck[$index]" ng-value="$index" />

If you want to update the studentmodel to know if it is checked or not, you could try using ng-change:

如果您想更新student模型以了解它是否被选中,您可以尝试使用ng-change

<input type="checkbox" ng-model="studcheck[$index]" ng-value="$index" ng-change="student.checked = !student.checked" />