我在范围内有一系列对象,我用ng-repeat循环。我想根据它们的值过滤掉一些元素,但似乎完全忽略了ng-if。
我设置了这个简单的插图来说明:http://plnkr.co/edit/Aj0hpZQTfnkQ6BYG8DRb 这是控制器:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.events = [
{key: "ClassName", value: "exception", age:12},
{key: "Message", value: "oops", age: 25},
{key: "Stack", value: null, age: 35}
]
});
HTML模板:
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.0.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js" data-semver="1.0.8"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<ul>
<li ng-repeat="event in events" ng-if="event.age > 20">
[{{$index + 1}}] {{event.key}}: {{event.value}} - {{event.age}}
</li>
</ul>
</body>
</html>
ng-if
指令应该过滤掉数组的第一个元素,无论如何都要显示它。我错过了哪些忽略了ng-if?
答案 0 :(得分:4)
我认为正确的方法是使用过滤器,例如:
<li ng-repeat="event in events | filter:greaterThan">
答案 1 :(得分:1)
I've updated your Plunkr to solve your issue using the code below.
我经常使用两个自定义角度模块FilterIncludeIf
和UtilCompare
来为ng-if
提供类似ng-repeat
的功能。
FilterIncludeIf
将UtilCompare
作为依赖项并使用两个参数。第一个是字符串形式的比较运算符(在您的情况下为">="
)。
第二个是Object
。 键应设置为从ng-repeat
语句(下例中为customer
)返回的各个对象的键,其值为您要比较的值。 值应设置为您要比较的值。
查看example-snippet.html
,includeIf
最终会过滤customers.all
,并确保呈现的唯一customer
是以下所有语句都是{{1} }}
true
示例-snippet.html 强>
customer[firstname] != customers.all.current.data.firstname`
customer[lastname] != customers.all.current.data.lastname`
customer[email] != customers.all.current.data.email`
过滤 - includeIf
<li
ng-repeat="customer in customers.all | filter:query | includeIf : '!=' : {
firstname : customers.current.data.firstname,
lastname : customers.current.data.lastname,
email : customers.current.data.email,
}"
class="tab"
>
<div class="info">
<h4 class="subheader name">
{{customer.firstname}} {{customer.lastname}}
</h4>
{{customer.email}}
</div>
</li>
工厂 - 比较
angular
.module('FilterIncludeIf', [
'UtilCompare'
])
.filter('includeIf', function (compare) {
return function (items, comparator, attrs) {
var filteredInput = [];
for (var i = 0; i < items.length; i++) {
var item = items[i],
numOfAttrs = 0,
numOfMatchedAttrs = 0;
for (var key in attrs) {
numOfAttrs++
var value = attrs[key],
comparison = compare
.these(item[key], value)
.by(comparator)
.eval();
if (comparison) numOfMatchedAttrs++;
}
if (numOfAttrs == numOfMatchedAttrs) filteredInput.push(item);
}
return filteredInput
};
});
答案 2 :(得分:0)