kipris kipris - 2 months ago 20
AngularJS Question

Angular ng-repeat filtering

I have a deeply nested object. I have some records which contain 2 fields that show keys of object properties. I also have select needed to search records by property of object and input to search by key of object. So if I choose option1 and type in input some text, it will be shown the matches in the first field (not second!). And it's similar for second field.



How I try to realize:

I wrote a filter http://plnkr.co/edit/z9DEmfYz2grW9UonLcFK?p=preview

.filter('appFilter', function() {
return function(value, select, input) {

var result = [];
input = input.toLowerCase();
var reg = new RegExp(input,'g');

if (angular.isArray(value)) {
if (input === '' || $scope.isFiltering) {
return value;
} else if (select.value === 'Sequence') {
for (let i = 0; i < value.length; i++) {
if (value[i].Sequence.toLowerCase().match(reg)) {
result.push(value[i]);
}
}
return result;
} else if (select.value === 'ID') {
for (let i = 0; i < value.length; i++) {
if (angular.isArray(value[i].Document)) {
for (let j = 0; j < value[i].Document.length; j++) {
if (value[i].Document[j].ID.toLowerCase().match(reg)) {
result.push(value[i]);
}
}

}
}
return result;
} else {
console.log('error');
}
}
}
})


In controller I set to select's ng-model first option:
$scope.selectParameter = $scope.parameter[0];


In debug I set to input parameter some value (123 for example).


So I searching record by first field that contains 123 value. And result finds and pushes the object. But in browser shows anything.


What's the problem? And I can't avoid the empty option with '?' value in my select :(

UPDATED

Nearly solve my problem: http://plnkr.co/edit/z9DEmfYz2grW9UonLcFK?p=preview

It filters by appropriate field and input value. But I faced with another troubles.

When input is empty it doesn't show any record. And second is when I choose second option (ID) filter duplicates some records.

Also I try to switch off filter without clearing the input text by clicking on checkbox.

It's what I want to do but it doesn't work:


else if (input === '' || $scope.isFiltering) {
return value;
}


$scope.isFiltering
is
ng-model
for checkbox input

Answer

I tried using angulars default filter. I'm not sure if this is exactly what you want, but maybe it helps a little.

.filter('appFilter', function($filter) {
  return function(value, select, input) {
    if( !angular.isDefined(input) || input.length < 1) {
      return value;
    }

    // Angulars "filter" lets you pass in a object-structure to search for nested fields.
    var query = 
        (select.value === 'Sequence') ?
            {Sequence:input} : {Document:{ID:input}};

    return $filter('filter')(value, query);
  }
})

http://plnkr.co/edit/Egkw9bUvTPgooc0u2w7C?p=preview