kslstn kslstn - 3 months ago 12
AngularJS Question

How to filter array depending on url parameter

How can one filter an array for one property depending on an url parameter defined as true or not? I have tried the following, but: "Error: $location is not defined". I have made it available to the controller of the template though.

javascript:

app.filter('myFilter', function() {

return function( items ) {
return items.filter(function(element){
var ext = ($location.search().ext == "true"); // Check if url contains ?ext=true
if (ext == true){
if ( externallyAvailable == 'true') {
return true;
}
}
else{
return true;
}
});
}
});

app.controller('tilesController', ['$scope', '$http', '$sce', '$location', '$filter', function($scope, $http, $sce, $location, $filter) {
/* some controller logic */
}


Template:

<li ng-repeat="tile in list.tiles | myFilter" class="tile-wrapper">
<!-- content -->
</li>


I also find that my solution, if it would work, takes more lines than I'd expect, so other suggestions are welcome.

Answer

You need to inject the $location Provider in your filter as well. As you haven't done that, That is why it is showing you the undefined error. Try something like this

app.filter('myFilter', function($location) {

    return function( items ) {
        return items.filter(function(element, $location){
            var ext = ($location.search().ext == "true"); // Check if url contains ?ext=true
            if (ext == true){
                if ( externallyAvailable == 'true') {
                    return true;
                }
            }
            else{
                return true;
            }
        });
    }
});