8

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 ?

4

2 回答 2

12

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

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

由于某些 CDN 链接已损坏,因此更新了 plunk。

于 2012-09-25T09:48:12.203 回答
1

我相信最好的方法是将属性“isSelected”添加到您的记录中并绑定到该值。像这样的东西:

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

您可以做的另一件事(特别是如果您“不能”将该额外属性添加到记录中,将是维护一个选定项目的数组,并在用户进行选择时从选定的数组中添加/删除它们:

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

recordSelected 函数将在您的控制器中处理,以从选定的记录列表中添加/删除和记录。

PS:我用了一个否定的记录id来表示该记录未被选中。

于 2014-07-11T18:26:17.877 回答