Javascript 使用$filter根据数组中对象的属性进行筛选
假设以下数据:Javascript 使用$filter根据数组中对象的属性进行筛选,javascript,angularjs,angularjs-filter,Javascript,Angularjs,Angularjs Filter,假设以下数据: var roster = [ { id: 1, attended: true, person: {printName: 'Larry'}}, { id: 2, attended: false, person: {printName: 'Curly'}}, { id: 3, attended: true, perso
var roster = [
{
id: 1,
attended: true,
person: {printName: 'Larry'}},
{
id: 2,
attended: false,
person: {printName: 'Curly'}},
{
id: 3,
attended: true,
person: {printName: 'Moe'}}];
我试图找到数组中有人参与的对象数为真。我尝试了以下方法:
rosters.html:
{{ (roster | filter:{attended:true} ).length }}
checkedInCount: function() {
return $filter('filter')($scope.roster, attended.true).length;
}
rosters controller.js:
{{ (roster | filter:{attended:true} ).length }}
checkedInCount: function() {
return $filter('filter')($scope.roster, attended.true).length;
}
html过滤器按预期工作,在本例中返回2。但是,函数版本遇到错误
ReferenceError:找不到变量:attended
。我假设函数中遗漏了一些琐碎的东西,但我不确定它是什么。使用对象作为表达式:
return $filter('filter')($scope.roster, { attended: true }).length;
请仔细比较你的两个版本。如果你找不到到底发生了什么,请看一看这些论点。谢谢你指出这一点。我浏览了那一页,但我完全误解了如何构建
表达式
参数。在看到@tasseKATT的答案后,现在完全有道理了。下面的选民能解释一下吗?我的问题原来有一个简单的答案,但我不认为它是穷人根据。非常感谢,我踢自己没有看到之前。