如何在angularjs中仅获取选定的复选框? [英] How to get only selected checkboxes in angularjs?
问题描述
我有 ng-repeat
ed 数据,并且正在尝试仅获取用户选择的数据.我不知道该怎么做,这就是我所拥有的:
HTML:
<ul><li data-ng-repeat="记录在记录中"><input type="checkbox" ng-model="record.Id">{{记录.Id}}<a href="javascript:;"data-ng-click="ShowSelected()">Show Selected
JS:
function MyCtrl($scope){$scope.records = [ { "Id": 1 }, { "Id": 2 }, { "Id": 3 } ];$scope.ShowSelected = function(){//我怎样才能在这里只获取选定的记录?}}
我确实让它以一种方式工作 - 通过向每个对象添加一个 isSelected:false
属性并将复选框的 ng-model
更改为 record.isSelected
,然后我可以在 ShowSelected
函数中过滤它.但这似乎效率低下,如果可以避免的话,我不想为模型添加额外的属性.
有更好的方法吗?
JavaScript
var app = angular.module('plunker', ['ui']);app.controller('MyCtrl', function($scope) {$scope.records = [ { "Id": 1 }, { "Id": 2 }, { "Id": 3 } ];$scope.selected = {};$scope.ShowSelected = function() {$scope.records = $.grep($scope.records, function( record ) {返回 $scope.selected[record.Id];});};});
HTML
<ul><li data-ng-repeat="记录在记录中"><input type="checkbox" ng-model="selected[record.Id]">{{记录.Id}}<a href="javascript:;"data-ng-click="ShowSelected()">Show Selected
您可以单独存储标志并使用它来过滤数据.
更新了 plunk,因为一些 CDN 链接已损坏.
I have ng-repeat
ed data, and am trying to get only the ones the user has selected. I'm not sure how to do it though, this is what I have:
HTML:
<div data-ng-controller="MyCtrl">
<ul>
<li data-ng-repeat="record in records">
<input type="checkbox" ng-model="record.Id"> {{record.Id}}
</li>
</ul>
<a href="javascript:;" data-ng-click="ShowSelected()">Show Selected</a>
</div>
JS:
function MyCtrl($scope)
{
$scope.records = [ { "Id": 1 }, { "Id": 2 }, { "Id": 3 } ];
$scope.ShowSelected = function()
{
// how can I get only the selected records here ?
}
}
I did get it working one way - by adding a isSelected:false
property to each object and changing the ng-model
of the checkbox to record.isSelected
, I can then filter on that in the ShowSelected
function. This seems inefficient though, I don't want to be adding extra properties to the model if can avoid it.
Is there a better way ?
JavaScript
var app = angular.module('plunker', ['ui']);
app.controller('MyCtrl', function($scope) {
$scope.records = [ { "Id": 1 }, { "Id": 2 }, { "Id": 3 } ];
$scope.selected = {};
$scope.ShowSelected = function() {
$scope.records = $.grep($scope.records, function( record ) {
return $scope.selected[ record.Id ];
});
};
});
HTML
<div data-ng-controller="MyCtrl">
<ul>
<li data-ng-repeat="record in records">
<input type="checkbox" ng-model="selected[record.Id]"> {{record.Id}}
</li>
</ul>
<a href="javascript:;" data-ng-click="ShowSelected()">Show Selected</a>
</div>
You can store the flag in separately and use it to filter the data.
updated plunk as some CDN links were broken.
这篇关于如何在angularjs中仅获取选定的复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!