【问题标题】:How to pass filter to a directive in AngularJS如何将过滤器传递给AngularJS中的指令
【发布时间】:2016-04-26 14:41:38
【问题描述】:

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

指令:

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>

【问题讨论】:

  • 正如@AmyBlankenship 的回答所述,您不需要将其注入或传递给指令定义。它应该对模板可用。如果不是,那么您可能需要检查该过滤器是否可用于定义您的指令的模块。

标签: angularjs filter directive


【解决方案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/

【讨论】:

  • 我知道我可以使用一个函数,但无论如何我可以通过我想要的过滤器,还是不可能?
  • 可以通过在compile 函数中操作模板来做到这一点。你不想那样做。您还可以自己编译包含过滤器名称的 HTML 片段。你也不想要那个(无缘无故太复杂)。我不知道有任何其他方式structurally 动态更改模板。另一方面,您可以实现一个元过滤器,它执行上面filterFn 所做的工作,但在过滤器的包装中。如果有用,我会更新问题。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-06
    • 2014-06-10
    • 2012-07-29
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多