我已经ng-repeat编辑了数据,并试图仅获取用户已选择的数据。我不确定该怎么做,这就是我所拥有的:
ng-repeat
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并将复选框的更改为record.isSelected,然后可以在ShowSelected函数中对此进行过滤。但是,这似乎效率很低,如果可以避免,我不想在模型中添加额外的属性。
isSelected:false
ng- model
record.isSelected
ShowSelected
有没有更好的办法 ?
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 ]; }); }; });
<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
您可以将标志分别存储在其中,并使用它来过滤数据。