How to get only selected checkboxes in angularjs?

后端 未结 2 1019
自闭症患者
自闭症患者 2020-12-16 03:35

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:

相关标签:
2条回答
  • 2020-12-16 04:10

    I believe the best way would be to add property 'isSelected' to your record and bind to that value. Something like this:

    <input type="checkbox" ng-model="record.isSelected">
    

    another thing you can do (specially if you 'cannot' add that extra property to the record, would be to maintain an array of selected items and add/remove them from the selected array when the user makes the selection:

    <input type="checkbox" ng-change="recordSelected(result)" ng-true-value="{{record.id}}" ng-false-value="{{-record.id}}" ng-model="result">
    

    The recordSelected function will be handled in your controller to add/remove and record from the selected records list.

    PS: I used a negative record id to represent the record was unselected.

    0 讨论(0)
  • 2020-12-16 04:23

    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>
    

    http://plnkr.co/edit/lqtDQ6

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

    updated plunk as some CDN links were broken.

    0 讨论(0)
提交回复
热议问题