Reputation: 105
I'm using AngularJS and filter option, like this:
<input type="checkbox" name="{{cat}}" ng-model="ctrl.filter[cat]" id='{{$index}}' class='chk-btn styled-checkbox' ng-click="removeAnother();"/>
This works very good. When I select an item, its getting right values. But I don't need multiple select so I wanna convert checkboxes to radio buttons.
If I use radio button, our functions not working. Please check the 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>
Thanks.
Upvotes: 0
Views: 43
Reputation: 38253
You just need to add ng-value="true"
so that the radio button will reflect the model value:
<input type="radio" ng-model="ctrl.filter[category]" ng-value="true" />
Then some directives to handle toggling:
<input ng-click="filter = !filter" ng-value="!filter" ng-checked="filter" type="radio" ng-model="ctrl.filter[category]" />
Upvotes: 3