我想通过选中一个按钮来显示非活动用户。
这是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,我没有找到一种有趣的方法来做到这一点。你能帮我找个解决方案吗?
谢谢:)
答案 0 :(得分:3)
就这样做:
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>
答案 1 :(得分:0)
最简单的方式!!您可以在点击事件中设置过滤器的值。
<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">
首先,您需要设置&#34; myCtrl.js&#34;的控制器名称实例。无论你的控制器名称。
答案 2 :(得分:0)
我个人喜欢使用过滤功能来过滤数据。这种方法很灵活,可以轻松地与其他表单变量进行交互。从angular docs开始,过滤器表达式可以是:
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将被更改以适应过滤器功能。具体来说,我将复选框绑定到$scope
函数在其逻辑中使用的$scope.showInactives
变量(filterFunc
)。当然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>
如果您需要任何其他复杂的逻辑,过滤功能可以让您获得很大的自由。它唯一需要返回的是布尔值(true或false)。
与过滤无关,我还必须通过将<th>
放在表格行<tr>
中来修复表格的HTML。