我想通过选中按钮来选择显示非活动用户。
下面是users
数组:
$scope.users = [
{firstname: 'Paul', inactive: true},
{firstname: 'Mark', inactive: false},
{firstname: 'Maggie', inactive: false},
{firstname: 'Lucy', inactive: true}
];
和显示它的表格:
<table>
<thead>
<th>Firstname</th>
<th>Activity</th>
</thead>
<tbody>
<tr ng-repeat="user in users | filter: ??">
<td>{{user.firstname}}</td>
<td>{{user.inactive}}</td>
</tr>
</body>
</table>
<input type="checkbox" ng-click="showInact()">Show inactives
我正在学习AngularJS,我没有找到一种有趣的方法来做到这一点。你能帮我找到解决方案吗?
谢谢:)
只需这样做:
1) 在您的控制器:
$scope.showInactive = false;
$scope.filterInact = function(item)
{
return item.inactive === $scope.showInactive;
};
$scope.showInact = function() {
$scope.showInactive = !$scope.showInactive;
}
2) 设置过滤器:
<tr ng-repeat="user in users | filter:filterInact">
<td>{{user.firstname}}</td>
<td>{{user.inactive}}</td>
</tr>
我个人喜欢使用过滤器函数来过滤数据。 此方法非常灵活,可以轻松地与其他表单变量进行交互。 从角度文档中,过滤器表达式可以是:
function(value, index)
:谓词函数可用于写入 任意过滤器。为数组的每个元素调用该函数。 最终结果是谓词的那些元素的数组 返回 true 为。
因此,示例筛选器函数可能如下所示:
$scope.filterFunc = function (user) {
//if the checkbox is checked show everyone, else only those that aren't inactive
return $scope.showInactives || !user.inactive;
};
并且 HTML 将被更改以适应过滤功能。 具体来说,我将复选框绑定到filterFunc
函数在其逻辑中使用的$scope
变量($scope.showInactives
)。 当然,ng-repeat
正在使用名为 filterFunc
.
<input type="checkbox" ng-model="showInactives"/>Show inactive users
<br/>
<table>
<thead>
<tr>
<th>Firstname</th>
<th>Activity</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users | filter:filterFunc">
<td>{{user.firstname}}</td>
<td>{{user.inactive}}</td>
</tr>
</tbody>
</table>
如果您需要任何其他复杂的逻辑,过滤器功能可以让您获得很大的自由。 它唯一需要返回的是布尔值(真或假)。
演示。
与过滤无关,我还必须通过将<th>
放在表格行<tr>
中来修复表格的 HTML。
最简单的方法!!您可以设置点击事件过滤器的值。
<tr ng-repeat="user in users | filter:filters">
<td>{{user.firstname}}</td>
<td>{{user.inactive}}</td>
</tr>
单击"筛选器设置为"复选框
<input type="checkbox" ng-click="filters.inactive = true">
首先,无论您的控制器名称如何,您都需要设置"myCtrl.js"的控制器名称。