如何将过滤器传递给AngularJS中的指令

时间:2016-01-20 16:28:03

标签: angularjs filter directive

我有一个自定义指令,我希望能够将过滤器名称传递给它。然后将在我的模板中使用该过滤器。这是我到目前为止所得到的:

指令:

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

模板:

<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title">{{ convertToDate({ dt: weatherObject.dt }) | date: dateFormat }}</h3>
    </div>
    <div class="panel-body">
        Daytime temperature: {{ weatherObject.temp.day | filterTemp }}
    </div>
</div>

2 个答案:

答案 0 :(得分:1)

您无需在控制器中访问它即可在视图中使用它。这就是过滤器的重点。如果你真的需要它在控制器中,你可以通过要求注入filterTempFilter来自行请求它。或者您可以注入$ filter提供程序并从中请求您的特定过滤器。

答案 1 :(得分:1)

一种非常简单的方法是,使用$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);
            };
        }
    }
}]);

缺点是您不能再将其用作过滤器:

    <div class="panel-body">
        Daytime temperature: {{ filterFn(weatherObject.temp.day) }}
    </div>

我想预期的过滤函数会返回一个原语(字符串,数字,布尔值)。如果它返回一些复杂的东西(对象,数组),则可能需要缓存返回值以避免无限的摘要周期。

您可以实施元过滤器:

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

将其用作:

    <div class="panel-body">
        Daytime temperature: {{ weatherObject.temp.day | metafilter:filterTemp }}
    </div>

这是展示元过滤器的小提琴:https://jsfiddle.net/opL1zfzd/