好的,下面是操作方法。
首先,让我们在您的文件中添加几行 CSS 以确保所有复选框都可见:
<style>
.row { margin-left: 0px }
input[type=checkbox] { margin-left: 30px; }
</style>
接下来,将以下行添加到您的控制器:
app.filter('unique', function() {
return function (arr, field) {
var o = {}, i, l = arr.length, r = [];
for(i=0; i<l;i+=1) {
o[arr[i][field]] = arr[i];
}
for(i in o) {
r.push(o[i]);
}
return r;
};
})
app.controller("maincontroller",function($scope){
$scope.query = {};
$scope.quer = {};
$scope.queryBy = '$';
$scope.isCollapsed = true;
$scope.selectedRefs = [];
$scope.myFilter = function (item) {
var idx = $scope.selectedRefs.indexOf(item.b);
return idx != -1;
};
$scope.toggleSelection = function toggleSelection(id) {
var idx = $scope.selectedRefs.indexOf(id);
if (idx > -1) {
$scope.selectedRefs.splice(idx, 1);
}
else {
$scope.selectedRefs.push(id);
}
};
呼。
由于某种原因,您的 Plunkr 版本的 AngularJS 无法识别 unique 属性,因此我在您的控制器中添加了一个。
最后,把你的 html 改成这样:
<div class="row">
<label data-ng-repeat="x in projects | unique:'b' | orderBy:'b'" >
<input
id="x.b"
type="checkbox"
ng-click="toggleSelection(x.b)"
ng-init="selectedRefs.push(x.b)"
ng-checked="selectedRefs.indexOf(x.b) > -1" />
{{x.b}}
</label>
</div>
...和你的 ng-repeat 到这个...
<tr ng-click="isCollapsed = !isCollapsed" ng-repeat-start="x in projects | filter:myFilter | orderBy:orderProp">
如果您有兴趣了解其工作原理,请添加以下行:
<div style="margin:10px 10px 30px 10px">
<pre>{{ selectedRefs }} </pre>
</div>
我喜欢这个技巧:您可以看到我们的“selectedRefs”数组的确切内容,并在我们勾选/取消勾选我们的复选框时看到它的变化。这在开发/测试我们的绑定时真的很有帮助!
如您所见,这些更改使用新的 unique 函数从 project 数组中获取不同值的列表,当页面首次加载时,我们将所有值推送到新的“@987654331 @" 数组。
["123","321","456","654","789","987"]
然后,当您勾选/取消勾选复选框时,我们会在此列表中添加/删除该项目。
最后,我们在ng-repeat 中使用该过滤器。
ng-repeat-start="x in projects | filter:myFilter | orderBy:orderProp"
任务完成!
更新
如果您想从所有复选框开始未勾选,那么这是一个简单的更改。只需删除这一行...
ng-init="selectedRefs.push(x.b)"
..并更改 myFilter 函数以最初显示所有项目..
$scope.myFilter = function (item) {
if ($scope.selectedRefs.length == 0)
return true;
var idx = $scope.selectedRefs.indexOf(item.b);
return idx != -1;
};
要添加“全部清除”按钮,只需在表单中添加一个按钮,该按钮调用 AngularJS 控制器中的函数,如下所示..
$scope.clearAll = function () {
$scope.selectedRefs = [];
};
(不过我还没有测试过这些建议。)