我有一个复杂的过滤器,并希望将其重构为指令。
让我们举一个简单的例子:
app.filter('tolower', function() {
return function(input) {
return input.toLowerCase(); //simple example
}
});
<div ng-bind-html="'TEST' | tolower"></div>
我怎么能重构这个,以便我可以使用如下指令:
<div tolower="TEST"></div>
答案 0 :(得分:2)
app.directive('tolower', function(tolowerFilter) {
return function(scope, element, attrs) {
element.html(tolowerFilter(attrs.tolower));
};
});
答案 1 :(得分:0)
在您的指令中添加带有'tolower'的范围,以便您可以将tolower用作属性:
.directive('MyDirective', function(config) {
...
scope: {
tolower: '='
},
...
});
然后,在你的控制器处理程序中:
function MyDirectiveController($filter) {
var vm = this;
...
vm.loweredValue = $filter('tolower')(vm.tolower);
...
}
最后,您可以通过将sortedValue注入元素的DOM中来使用lowerValue。