如何只获得angularjs中的选中复选框? [英] How to get only selected checkboxes in angularjs?

查看:601
本文介绍了如何只获得angularjs中的选中复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 ng-repeat ed数据,我试图只获取用户选择的数据。我不知道该怎么做,这就是我所拥有的:

I have ng-repeated 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 ?
    }
}

我确实以一种方式工作 - 通过添加 isSelected:false 每个对象的属性,并将复选框的 ng-model 更改为记录.isSelected ,然后我可以在 ShowSelected 函数中对其进行过滤。这似乎效率低下,我不想在模型中添加额外的属性,如果可以避免的话。

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.

有更好的方法吗?

推荐答案

JavaScript



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



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>

http://plnkr.co/edit/lqtDQ6

您可以单独存储该标志并使用它来过滤数据。

You can store the flag in separately and use it to filter the data.

这篇关于如何只获得angularjs中的选中复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆