我有一个元素列表,每个元素都有一个复选框。 我添加了一个 checkAll 按钮来选择我的所有元素。
http://jsbin.com/dipumemo/3 ( edit )
如何改进我的用户界面并在单击“checkAll”按钮时仅选择可见元素?
我的工作流程:
- 在过滤器中附加 1(隐藏显示:无;列表 2)
- 点击复选框全部
- 清除过滤器
- 仅查看 list1 已选中
我的 html:
<div ng-app="listsModule">
<div ng-controller="listsController">
<input type="text" id="filter_lists" ng-model="search" placeholder="Search a list">
<table>
<thead>
<tr>
<th><input type="checkbox" ng-model="checkAll"/></th>
<th>List name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="list in lists | filter:search | orderBy:'name'">
<td><input type="checkbox" ng-model="list.isSelected" ng-checked="checkAll"></td>
<td>{{ list.name }}</td>
<td>{{ list.isSelected }}</td>
</tr>
</tbody>
</table>
</div>
</div>
我的javascript:
var app = angular.module('listsModule', []);
app.controller('listsController', function ($scope) {
$scope.lists = [
{"id": 39, "name": "list1", "isSelected": false},
{"id": 40, "name": "list2", "isSelected": false}
]
});
最佳答案
更改列表的过滤方式将使您能够访问当前范围内的过滤列表。然后您可以从该过滤列表中获取您选择的项目。将 watch 添加到您的 checkAll 将使您可以切换筛选项目的选择。
html:
<div ng-app="listsModule">
<div ng-controller="listsController">
<input type="text" id="filter_lists" ng-model="search" placeholder="Search a list">
<table>
<thead>
<tr>
<th><input type="checkbox" ng-model="checkAll"/></th>
<th>List name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="list in filtered = (lists | filter:{name:search}) | orderBy:'name'">
<td><input type="checkbox" ng-model="list.isSelected"></td>
<td>{{ list.name }}</td>
<td>{{ list.isSelected }}</td>
</tr>
</tbody>
</table>
<div>Selected:
<div ng-repeat="list in filtered | filter:{isSelected:true} | orderBy:'name'">
{{list.name}}
</div>
</div>
</div>
</div>
JavaScript:
var app = angular.module("listsModule", []);
app.controller('listsController', ['$scope', function($scope) {
$scope.lists = [
{"id": 39, "name": "Fluffy", "isSelected": false},
{"id": 40, "name": "Muffy", "isSelected": false},
{"id": 41, "name": "Dingo Jr.", "isSelected": false},
{"id": 42, "name": "Bertram", "isSelected": false}
];
$scope.$watch('checkAll', function(newValue, oldValue) {
if ($scope.filtered)
for (i=0; i<$scope.filtered.length; i++) {
$scope.filtered[i].isSelected = newValue;
}
});
}]);
关于javascript - 如何在搜索结果中只选择可见元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21832069/