Ryan - Llaver Ryan - Llaver - 3 months ago 10
Javascript Question

Passing an ng-repeat variable is undefined

I am trying to get a custom filter to work in Angular using ng-repeat. The problem is my data is not being passed correctly.

My html:

<div class="card" ng-repeat="acqui in acquis | orderBy:'date':true | fieldFilter: this">


My filter:

.filter('fieldFilter', function() {
return function(acqui, $scope) {
if($scope.fieldFilter.length > 0) {
console.log($scope.fieldFilter);
for(let i = 0; i < $scope.fieldFilter.length; i++) {
if(acqui.field === $scope.fieldFilter[i]) {
return acqui;
}
}
} else {
return acqui;
}
}
});


I am trying to compare acqui from ng-repeat to a $scope variable, but for some reason acqui.field is undefined, I'm really at a loss as to what to try, even though I'm sure it's something simple.

Answer

You can't pass whole $scope to your angular filter(though it would have been bad way to just think of it). You could pass the filtered object just by mentioning it after filter name.

ng-repeat="acqui in acquis | orderBy:'date':true | fieldFilter: fieldFilter"

Filter

.filter('fieldFilter', function() {
    //fieldFilter will have passed `fieldFilter` object from `$scope`
    //where as `acquis` is an array.
    return function(acquis, fieldFilter) {
        if(fieldFilter.length > 0) {
            console.log(fieldFilter);
            for(let i = 0; i < fieldFilter.length; i++) {
                //here you have `acquis` not acqui
                //if(acqui.field === fieldFilter[i]) {
                //    return acqui;
                //}
            }
        } else {
            return acqui;
        }
    }
});