Devacron.com

Data filtering based on multiple checkboxes in AngularJs. [HowTo]

Ok, this is just a quick post with some small pieces of code which shows how to filter data, to be precise a json object and present them in view. As you already know AngularJs is powerfull stuff, and this lines of code prooves that one more time. Have a look:

First the html:

<html ng-app="myApp">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type='text/javascript' src="car.js"></script>
<body style="font-family:Verdana; font-size:14px;">
<div ng-controller="MyCtrl">
	<h4>Pick a brand to see the models</h4>
    <div ng-init="group = (cars | groupBy:'make')" style="width:100%">
        <div ng-repeat="m in group"   style="width:100px; float:left;">
            <b><input type="checkbox" ng-model="useMakes[$index]"/>{{m}}</b>
        </div>
    </div>
    <div style="clear:both;"></div>
    <div>
        <ul>
			<li  ng-repeat="car in cars | filter:filterMakes()"><p><b>{{car.make}} - {{car.model}}</b></p></li>
        </ul>    
    </div>
</div>
</body>
</html>

And the javascript below:

var myApp = angular.module('myApp',[]);

function MyCtrl($scope, filterFilter) {
    $scope.useMakes = [];
    
    $scope.filterMakes = function () {
        return function (p) {
            for (var i in $scope.useMakes) {
                if (p.make == $scope.group[i] && $scope.useMakes[i]) {
                    return true;
                }
            }
        };
    };
    
    $scope.cars = [
        {model: '316', make: 'Bmw'},
        {model: '520', make: 'Bmw'},
        {model: 'Fiesta', make: 'Ford'},
        {model: 'Focus', make: 'Ford'},
        {model: 'Clio', make: 'Renault'},
		{model: 'Toledo', make: 'Seat'},
		{model: 'Leon', make: 'Seat'},
		{model: 'Insignia', make: 'Opel'},
		{model: 'Astra', make: 'Opel'},
        {model: 'Corsa', make: 'Opel'}
    ];    
}


var uniqueItems = function (data, key) {
    var result = new Array();
    for (var i = 0; i < data.length; i++) {
        var value = data[i][key];
 
        if (result.indexOf(value) == -1) {
            result.push(value);
        }
    
    }
    return result;
};

myApp.filter('groupBy',
            function () {
                return function (collection, key) {
                    if (collection === null) return;
                    return uniqueItems(collection, key);
        };
    });

So as you can see the most important part is the creation of the filter groupBy. By creating this filter we can add it in the ng-repeat like this ng-repeat=”car in cars | filter:filterMakes()” and it checks each car in the json object.

Result

See it live here: http://jsfiddle.net/rzgWr/123/

 

Exit mobile version