How to pass filter to a directive in AngularJS

前端 未结 2 416
走了就别回头了
走了就别回头了 2021-01-22 05:11

I have a custom directive and I want to be able to pass a filter name to it. That filter will then be use in my template. Here is what I got so far:

the directive:

2条回答
  •  野性不改
    2021-01-22 05:47

    A very simple way is, using the $filter service and a function in the scope that delegates to the correct filter:

    angular.module('forecastDirective', [])
    .directive('forecast', ['appConfig', function(appConfig) {
        return {
            templateUrl: appConfig.directivesRoot + 'templates/forecast.html',
            replace: true,
            scope: {
                weatherObject: "=",
                convertToDate: "&",
                filterTemp: "@",
                dateFormat: "@",
            },
            controller: ['$filter', '$scope', function($filter, $scope) {
                $scope.filterFn = function(in) {
                    return $filter($scope.filterTemp)(in);
                };
            }
        }
    }]);
    

    A downside is that you can no longer use it as a filter:

        
    Daytime temperature: {{ filterFn(weatherObject.temp.day) }}

    I guess the intended filter function returns a primitive (string, number, boolean). If it returns something complex (object, array), you may need to cache return values to avoid infinite digest cycles.


    You can implement a meta-filter:

    angular.module(...)
        .filter('metafilter', ['$filter', function($filter) {
            return function(input, filterName) {
                return $filter(filterName)(input);
            };
        }]);
    

    Use it as:

        
    Daytime temperature: {{ weatherObject.temp.day | metafilter:filterTemp }}

    This is a fiddle demonstrating the metafilter: https://jsfiddle.net/opL1zfzd/

提交回复
热议问题