如何根据url参数过滤数组

时间:2016-08-15 09:20:05

标签: angularjs

如何根据定义为true的url参数过滤一个属性的数组?我尝试过以下方法,但是:“错误:$ location未定义”。我已经将它提供给模板的控制器了。

的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 */
}

模板:

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

我也发现我的解决方案,如果可行,需要的线路比我预期的要多,所以欢迎其他建议。

2 个答案:

答案 0 :(得分:1)

您还需要在过滤器中注入$ location Provider。由于你没有这样做,这就是为什么它向你显示未定义的错误。试试这样的事情

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;
            }
        });
    }
});

答案 1 :(得分:0)

您尝试使用$location 服务检查字符串(无论是否为UL字符串)

这是一个未经测试的开始,你可以使用:

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

    return function( items ) {
        return items.filter(function(element){
            return element.indexOf('?ext=true') !== -1;
        });
    }
});