developer developer - 4 months ago 51
AngularJS Question

AngularJS custom filter with checkbox and radio button

My application has to dynamically list file items using a Radio button, Checkbox and AngularJS custom filter (code given below).

I have tried few options, but could not get the working code.

I have created the fiddle link and find the same below:
https://jsfiddle.net/38m1510d/6/

Could you please help me to complete the below code to list the file items dynamically ?

Thank you.

<div ng-app="myApp" ng-controller="myCtrl">
<label>
<input type="radio" ng-model="inputCreatedBy" value="byX"
ng-click="myFilter(?, ?)"> by X&nbsp;&nbsp;&nbsp;&nbsp;
<input type="radio" ng-model="inputCreatedBy" value="byAll"
ng-click="myFilter(?, ?)"> by All&nbsp;&nbsp;&nbsp;&nbsp;
</label> <br/><br/>

<label>
<input type='checkbox' ng-model='Type1Files' ng-change='myFilter(?, ?)'>Type1 files&nbsp;&nbsp;&nbsp;&nbsp;
<input type='checkbox' ng-model='Type2Files' ng-change='myFilter(?, ?)'>Type2 files&nbsp;&nbsp;&nbsp;&nbsp;
</label>

<br/><br/>
<label ng-repeat="file in displayFiles | filter: myFilter(createdBy, fileType)">
{{ file.name }}
</label>

</div>
</body>
<script>
var app = angular.module("myApp",[]);

app.controller('myCtrl', function ($scope) {

$scope.files = [
{ name: 'file1', type:'Type1', createdBy: 'X' },
{ name: 'file2', type:'Type2', createdBy: 'X' },
{ name: 'file3', type:'Type2', createdBy: 'Y' },
{ name: 'file4', type:'Type1', createdBy: 'Y' }
];

$scope.displayFiles = [];

$scope.myFilter = function() {
return new function(createdBy, fileType) {
var displayFilesTemp = [];
for(i=0;i<$scope.files.length;i++) {
if($scope.files[i].type ==fileType && $scope.files[i].createdBy == createdBy && !checkArrayContainsObject(displayFilesTemp, displayFiles[i])) {
displayFilesTemp.push(displayFiles[i]);
}
}
return displayFilesTemp;
};
};
});

function checkArrayContainsObject(a, obj) {
for (var i = 0; i < a.length; i++) {
if (JSON.stringify(a[i]) == JSON.stringify(obj)) {
return true;
}
}
return false;
}
</script>

Answer

Here's a working fiddle - http://jsfiddle.net/1gfaocLb/

Radio is a unique value, so it's easy to filter by. Selected types are array of values so it's needs a little more attention.

myApp.filter('typesFilter', function() {
   return function(files, types) {
        return files.filter(function(file) {
          if(types.indexOf(file.type) > -1){
            return true;
          }else{
            return false;
          }
        });
    };
});
Comments