我试图通过我存储为元数据的过滤字符串使用过滤器表达式来调用$ filter。例如,我的过滤字符串可能如下所示:
var filterForMyValue = "number : 2 | someOtherFilter";
这是没有问题我通过标记调用类似的硬编码过滤器:
<span>{{ somevalue | number : 2 | someOtherFilter</span>
但是我想以编程方式应用此过滤器。执行类似$filter(myFilterString)(valueToFilter)
之类的操作不起作用,因为您不能将过滤器参数或多个链接过滤器包含为单个字符串。它只允许您传递过滤器名称,然后必须单独传递参数,这是我不想要的,因为这是一个需要将任何过滤器字符串应用于值的通用方法。我认为$ parse可能有一些用处,但我无法找到任何与$ filter结合使用的例子来实现这一点。
答案 0 :(得分:2)
这与bluetoft评论相似,可能使用解析器服务而不是编译更近一步。
http://plnkr.co/edit/ZyFZ42XAuuE4tRZbxKqn?p=preview
$scope.item = 1.123;
//Option 1
var filterFn = $parse('item |number:2|myFilter');
console.log(filterFn($scope));
//Option 2
$scope.item = $filter('number')($scope.item, 2);
$scope.item = $filter('myFilter')($scope.item);
console.log($scope.item);
有两种选择。 Option1使用解析器和选项可能是您可以创建自定义过滤器链服务(这是解析器服务内部会执行的操作,但这更符合您传递输入/过滤器的预期模式)。
答案 1 :(得分:1)
我不知道有什么方法可以完全按照你的要求行事,但我认为$ compile服务可能会在另一个庄园中提供一些帮助。
var app = angular.module('myApp',[]);
app.filter('myFilter',function(){
return function(val){
return val * 2;
}
});
app.directive('myDirective',function($compile){
return {
restrict:'E',
link: function(scope,element){
scope.filterForMyValue = "number : 2 | myFilter";
scope.item = 1.123;
var format = '<span>{{item |' + scope.filterForMyValue + '}}</span>';
var compiled = $compile(format)(scope);
element.append(compiled);
}
}
});