I have a scenario where I want the user to be able to select which filter to apply. I do not want to maintain a separate list of filters in the html. So considering the following code where I am trying to access the names of the registered filters. (I am an AngularJS newbie so apologies if this is obvious)
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']
});
I guess there is no build in way of doing this. But you can get this information if you are hooking in the $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);
})
The filters
value may now be used in your controller by injecting it:
.controller('MainCtrl', function(filters){
// outputs an array with all known filters
console.log(filters);
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.