我有一个自定义指令,我希望能够将过滤器名称传递给它。然后该过滤器将在我的模板中使用。这是我到目前为止所得到的:
指令:
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
服务和委托(delegate)给正确过滤器的作用域中的函数:
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>
我猜预期的过滤函数返回一个原语(字符串、数字、 bool 值)。如果它返回一些复杂的东西(对象、数组),您可能需要缓存返回值以避免无限的摘要循环。
您可以实现元过滤器:
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>
这是一个演示元过滤器的 fiddle :https://jsfiddle.net/opL1zfzd/
关于angularjs - 如何将过滤器传递给 AngularJS 中的指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34905351/