我正在使用AngularJS和过滤器选项,如下所示:
<input type="checkbox" name="{{cat}}" ng-model="ctrl.filter[cat]" id='{{$index}}' class='chk-btn styled-checkbox' ng-click="removeAnother();"/>
这非常好用。当我选择一个项目时,它的值正确。但我不需要多个选择,所以我想将复选框转换为单选按钮。
如果我使用单选按钮,我们的功能无效。请查看 demo.
(function() {
'use strict';
angular.
module('myApp', []).
controller('WineCtrl', WineCtrl);
// Functions - Definitions
function WineCtrl() {
// Variables - Private
var self = this;
// Variables - Public
self.filter = {};
self.wines = [{
name: 'Wine A',
category: 'red'
},
{
name: 'Wine B',
category: 'red'
},
{
name: 'Wine C',
category: 'white'
},
{
name: 'Wine D',
category: 'red'
},
{
name: 'Wine E',
category: 'red'
},
{
name: 'Wine F',
category: 'white'
},
{
name: 'Wine G',
category: 'champagne'
},
{
name: 'Wine H',
category: 'champagne'
}
];
// Functions - Public
self.filterByCategory = filterByCategory;
self.getCategories = getCategories;
// Functions - Definitions
function filterByCategory(wine) {
return (self.filter[wine.category] || noFilter(self.filter)) ? 'show' : 'hide';
}
function getCategories() {
return (self.wines || []).
map(function(wine) {
return wine.category;
}).
filter(function(wine, idx, arr) {
return arr.indexOf(wine) === idx;
});
}
function noFilter(filterObj) {
return Object.
keys(filterObj).
every(function(key) {
return !filterObj[key];
});
}
}
}());
.hide {
opacity: 0.5;
}
.show {
opacity: 1;
}
<div ng-controller="WineCtrl as ctrl">
<b>Category:</b>
<div ng-repeat="category in ctrl.getCategories()">
<label>
<input type="radio" ng-model="ctrl.filter[category]" />
{{ category }}
</label>
</div>
<hr />
<div ng-repeat="wine in ctrl.wines">
<div class="{{ctrl.filterByCategory(wine)}}">
{{ wine.name }} <i>({{ wine.category }})</i>
</div>
</div>
<hr />
<b>Number of results: {{ filteredWines.length }}</b>
</div>
感谢。
答案 0 :(得分:3)
您只需添加ng-value="true"
,以便单选按钮将反映模型值:
<input type="radio" ng-model="ctrl.filter[category]" ng-value="true" />
然后处理切换的一些指令:
<input ng-click="filter = !filter" ng-value="!filter" ng-checked="filter" type="radio" ng-model="ctrl.filter[category]" />