简体   繁体   中英

How to filter results based on checkbox selection in angular

I have 3 checkboxes, and I want to filter my list of results based on selection of checboxes. I am forming an array of selection and have applied filter using angular, but when I click on a checkbox, the results or listing disappears

HTML

<div class="row" ng-controller="DataCtrl">
    <div class="col-sm-4">
        <div class="checkbox">
            <label>
                <input type="checkbox" value="US" ng-click="select('US')">
                US
            </label>
        </div>
        <div class="checkbox">
            <label>
                <input type="checkbox" value="UK" ng-click="select('UK')">
                UK
            </label>
        </div>
        <div class="checkbox">
            <label>
                <input type="checkbox" value="Australia" ng-click="select('Australia')">
                Australia
            </label>
        </div>
    </div>
    <div class="col-sm-8">
        <div class="well" ng-repeat="eve in events | filter : selected_country">
            <h3>{{eve.title}}</h3>
            <h5>{{eve.country}}</h5>
        </div>
    </div>
</div>

Controller

refine.controller('DataCtrl', function($scope){
$scope.selected_country = [];
$scope.events = [
    {
        'title' : 'Global Warming 2016',
        'country' : 'US'
    },
    {
        'title' : 'Global Warming 2017',
        'country' : 'UK'
    },
    {
        'title' : 'Global Warming 2018',
        'country' : 'Australia'
    }
];

$scope.select = function(country){
    var index = $scope.selected_country.indexOf(country);
    var country_exists = (index > -1);
    if(country_exists == false){$scope.selected_country.push(country);}
    else{ $scope.selected_country.splice(index, 1);}
    console.log($scope.selected_country);
}

});

it seems you wrote your conditions wrong, try changing

if(country_exists == false){$scope.selected_country.push(country);}

to

if(country_exists == true){$scope.selected_country.push(country);}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM