当使用过滤器VS在Angularjs指令
问题描述:
这是一个简单的问题 - 它可能已被问(只是无法找到它。)
It's a simple question - and it may have been asked (just couldn't find it..)
当你使用过滤器在一个指令,当涉及到操纵数据,反之亦然?
When would you use a filter over a directive when it comes to manipulating the data, or vice versa?
在一个非常非常简单的例子,看到这个 Plunkr
In a really really simple example, see this Plunkr
从本质上讲,我有如下的的JavaScript
Essentially, I have the following javascript
var app = angular.module('app', []);
app.controller('MyCtrl', ['$scope', function($scope){
$scope.testMessage = 'Some Text'
}]);
app.directive('myDirective', function(){
return{
restrict: 'A',
link: function(scope, element, attrs){
// do some stuff with the data
//
element.html(scope.testMessage + ' result of my directive');
}
}
});
app.filter('myFilter', function(){
return function(text){
// do something with text
return text + ' & result of my filter';
}
});
和下面的 HTML
<body ng-controller="MyCtrl">
<div my-directive ng-model="testMessage" ></div>
<br />
<div>{{ testMessage | myFilter }}</div>
</body>
所以,你什么时候会使用一个比其他?
So when would you use one over the other?
答
一些提示(非详尽列表):
Some hints (non-exhaustive lists):
使用它的时候...
- 您想要做的DOM结构操作
- 您要添加的行为(控制器)
- 的结果是依赖于其他合作者(该指令的
要求
配置)
- You want to do structural manipulation of the DOM
- You want to add behaviour (the controller)
- The outcome is dependent on other collaborators (the
require
configuration of the directive)
使用它的时候...
- 您要变换值到另一个(例如串RARR;日)
- (上面的子集,但重要的是要保证它自己的子弹:)当您要变换数组(如要显示在重复的元素 -
过滤器
过滤器NG-重复
)
- You are transforming a value to another (e.g. String → Date)
- (Subset of the above, but important to warrant it's own bullet:) When you are transforming an array (e.g. to be displayed in repeated elements - the
filter
filter andng-repeat
)