曾几何时,这是有效的,但不知何故它被打破了。我希望能够使用 ng-repeat 生成复选框,以根据存储的数据获取所需数量的复选框,并使用它们来过滤生成的表格。
此外,我不希望重复复选框的相同值。
我已经用代码做了一个 plnkr。
<div class="row">
<label data-ng-repeat="x in projects">
<input
type="checkbox"
data-ng-true-value="{{x.b}}"
data-ng-false-value=''
ng-model="quer[queryBy]" />
{{x.b}}
</label>
</div>
http://plnkr.co/edit/RBjSNweUskAtLUH3Ss6r?p=preview
总结一下。
用于过滤
Ref
的复选框。复选框是独一无二的。
使用
Ref
根据ng-repeat
创建复选框。
最佳答案
好的,下面是操作方法。
首先,让我们在您的代码中添加几行 CSS 以确保所有复选框都可见:
<style>
.row { margin-left: 0px }
input[type=checkbox] { margin-left: 30px; }
</style>
接下来,将以下行添加到您的 Controller :
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
属性,因此我向您的 Controller 添加了一个。
最后,将您的 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
”数组的确切内容,并看到它在我们勾选/取消勾选复选框时发生变化。这在开发/测试我们的绑定(bind)时真的很有帮助!
如您所见,这些更改使用新的 unique
函数从 project
数组中获取不同值的列表,当页面首次加载时,我们推送所有值都放入我们新的“selectedRefs
”数组中。
["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 Controller 中调用一个函数。
$scope.clearAll = function () {
$scope.selectedRefs = [];
};
(不过我还没有测试这些建议。)
关于javascript - 如何使用 Angularjs 的 ng-repeat 复选框过滤表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30976425/