如何将过滤器传递给AngularJS中的指令 [英] How to pass filter to a directive in AngularJS

查看:79
本文介绍了如何将过滤器传递给AngularJS中的指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

指令:

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>

推荐答案

一种非常简单的方法是使用$filter服务和作用域中的一个委派给正确过滤器的函数:

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:

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

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

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

用作:

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

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

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

这篇关于如何将过滤器传递给AngularJS中的指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆