是否可以将 ng-repeat
的当前元素传递给自定义过滤器?
有点像这样(HTML):
<ul>
<li ng-repeat="row in rows | myFilter:row:anotherArgument>{{row}}</li>
</ul>
和(Javascript):
angular.module('myApp', [])
.filter('myFilter', function() {
return function(items, item, arg) {
// Do something here
}
});
我正在处理的数据看起来像这样(简化):
[
{
"id":"52d7d22867960cb905e1c5b3",
"label":"Model A",
"children":[
{
"id":"52d7d22967960cb905e1c5bf",
"type":"Page",
"label":"Sample Page A",
"class":"page",
"children":[...],
"watched":false
},
{...},
{
"id":"52d7d22967960cb905e1c5bd",
"label":"Page",
"class":"type"
}
],
"class":"model",
"watched":false
},
{...}
]
所以基本上我有一个树状结构,在第一层,可能有一个或多个带有 "class":"type"
的元素。嵌套数据由 Nick Perkins 处理 angular-bootstrap-nav-tree指示。
我只想显示具有 "watched":true
的元素。问题当然是 "class":"type"
的元素没有 watched
属性。
tl;dr
过滤掉 "watched":false
但保留带有 "class":"type"
最佳答案
不像您正在使用的那样,但有多种方法可以将行作为一个整体和单独使用。
如果您需要在 ng-repeat
之前访问行的元素内容,你应该为整个数组编写过滤器:
<ul>
<li ng-repeat="row in rows | myFilter:anotherArgument"> ... </li>
</ul>
在过滤器定义中只使用整个数组:
angular.module('myApp', []).filter('myFilter', function() {
return function(items, anotherArgument) {
// here you can access each argument as you like
items.forEach(function(item) {
...
});
return items;
};
});
主要原因是row
在您遍历数组并且数组本身是整个 FilterChain 的结果 之前不存在。把数组想象成这样:
ng-repeat="row in (row | filter1 | filter2 | ...)"
但取决于你的目的myFilter
您可能只是想在重复本身的内容中应用该过滤器。
<ul>
<li ng-repeat="row in rows">
{{row | myFilter:anotherArgument}}
</li>
<ul>
如果您使用第一种方法,我建议您在将数组传递给 ng-repeat
之前在 Controller 中准备好数组。 .任何绑定(bind)(如 {{...}}
、ng-bind
或 ng-repeat
)中的过滤器链越复杂,在每个 angular.digest 循环中需要计算的越多。这可能会导致应用程序变慢。
更新 根据更新的问题:
在您的情况下,我猜自定义过滤器可能如下所示:
angular.module('myApp', []).filter('mySpecificFilter', function() {
return function(items) {
return items.filter(function(element) {
return element.watched || element['class'] === 'type';
}
}
});
关于javascript - 将当前元素传递给 ng-repeat 中的自定义过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21187517/