如何列出可用的过滤器

时间:2014-02-10 09:14:08

标签: javascript angularjs

我有一个场景,我希望用户能够选择要应用的过滤器。我不想在html中维护一个单独的过滤器列表。所以考虑下面的代码,我试图访问已注册过滤器的名称。 (我是AngularJS的新手,如果这很明显,请道歉)

angular.module('app.filters', []);

angular.module('app.filters').filter('filter1', function() {/* filter code */});

angular.module('app.filters').filter('filter2', function() {/* another filter code */});

angular.module('app', ['app.filters']);

angular.module('app').controller('MainCtrl', function ($scope, $filter) {

    /* How do I list filter1 and filter2 in here so that they can be output
       in a template? The below means the filter names are recorded twice */

    $scope.availableFilters = ['filter1', 'filter2']
});

1 个答案:

答案 0 :(得分:2)

我想没有建立这样做的方法。但是如果你在$filterProvider

中挂钩,你可以获得这些信息
.config(function($filterProvider, $provide) {
    // keep the original register fucntion
    var registerFn = $filterProvider.register;
    // array with all filters
    var allFilters = [];

    // replace the register function with our own implementation
    $filterProvider.register = function(name, fn){
        // save the name in the array
        allFilters.push(name);
        // call the original function
        registerFn(name, fn);
    }

    // register a value to retrieve the filters
    $provide.value('filters', allFilters);

}) 

现在可以通过注入来在控制器中使用filters值:

.controller('MainCtrl', function(filters){
   // outputs an array with all known filters
   console.log(filters);
})