Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

javascript - How to get only selected checkboxes in angularjs?

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 ?
    }
}

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...