我有一个要通过单选按钮过滤的项目列表,这是我的数组示例:
$scope.items = [
{
"name":"person 1",
"section":"one",
"job":false
},
{
"name":"person 2",
"section":"two",
"job":true
},
{
"name":"person 3",
"section":"one",
"job":false
},
{
"name":"person 4",
"section":"one",
"job":true
}
];
在我的HTML中,我有一个 ng-repeat 列表,我想使用单选按钮进行过滤:
<div class="menu">
<label>
<input type="radio" ng-model="filteradio.section" value="">
<p>All</p>
</label>
<label>
<input type="radio" ng-model="filteradio.section" value="one">
<p>Section 1</p>
</label>
<label>
<input type="radio" ng-model="filteradio.section" value="two">
<p>Section 2</p>
</label>
<label>
<input type="radio" ng-model="filteradio.job" value="true">
<p>People with job</p>
</label>
</div>
<table>
<tr>
<td>Name</td>
<td>Section</td>
<td>Job</td>
</tr>
<tr ng-repeat="item in items | filter:filteradio:strict">
<td>{{item.name}}</td>
<td>{{item.section}}</td>
<td ng-if="item.job">yes</td>
</tr>
</table>
问题在于最后一个单选按钮不起作用,因为当我选择带有“ filteradio.section” 的按钮时,它们可以正常工作,但是一旦单击在“ filteradio.job” 中,其他单选按钮保持选中状态!
我尝试为所有单选按钮添加相同的“ 名称属性”,但是一旦单击“ filteradio.job” ,所有项就会消失。
如何按“部门”和“如果有工作就”过滤它们?有没有更简单的方法来解决这个问题?
答案 0 :(得分:1)
我在下面提供了一个工作示例,但我将介绍一些值得注意的地方:
ng-model
上,否则您可能会处于选择了多个无线电输入的状态ng-change
更新此过滤器结构ng-value
而不是value
,后者的值将始终被解释为字符串文字。
angular
.module('app', [])
.controller('ctrl', function ($scope) {
var radioFilter = {
prop: 'section',
value: null,
};
$scope.items = [
{
name: 'person 1',
section: 'one',
job: false,
},
{
name: 'person 2',
section: 'two',
job: true,
},
{
name: 'person 3',
section: 'one',
job: false,
},
{
name: 'person 4',
section: 'one',
job: true,
}
];
$scope.radio = null;
$scope.radioChanged = function (prop) {
radioFilter = {
prop: prop,
value: $scope.radio,
};
};
$scope.filterByRadio = function (item) {
return $scope.radio === null || item[radioFilter.prop] === $scope.radio;
};
});
<div ng-app="app" ng-controller="ctrl">
<div>
<label>
<input type="radio" ng-model="radio" ng-change="radioChanged('section')" ng-value="null"> All
</label>
<label>
<input type="radio" ng-model="radio" ng-change="radioChanged('section')" value="one"> Section 1
</label>
<label>
<input type="radio" ng-model="radio" ng-change="radioChanged('section')" value="two"> Section 2
</label>
<label>
<input type="radio" ng-model="radio" ng-change="radioChanged('job')" ng-value="true"> People with job
</label>
</div>
<table>
<tr>
<td>Name</td>
<td>Section</td>
<td>Job</td>
</tr>
<tr ng-repeat="item in items | filter:filterByRadio">
<td>{{ item.name }}</td>
<td>{{ item.section }}</td>
<td>{{ item.job ? "yes" : "" }}</td>
</tr>
</table>
</div>
<script src="https://unpkg.com/angular@1.7.4/angular.min.js"></script>