我遇到了一個場景,我需要在某些迭代后有條件地在 ng-repeat 中執行 HTML。
下面是一個例子:
<div>
<p ng-init="x=1">
These are my names....
</p>
<div ng-repeat="a in data.result">
<div ng-if="a.type=='Student' && x<3">
<span ng-init="x ">
<br/>
{{::a.name}} with type of {{::a.type}} and color {{::a.color}}
</span>
</div>
</div>
</div>
腳本:
data.result =[
{
"color": "Red",
"name": "IP0",
"type": "Student"
},
{
"color": "Red",
"name": "IPwd1",
"type": "Student"
},
{
"color": "White",
"name": "IPdw2",
"type": "Teacher"
},
{
"color": "Red",
"name": "IPed3",
"type": "Student"
},
{
"color": "Red",
"name": "IP4ed",
"type": "Student"
},
{
"color": "White",
"name": "IP7h2",
"type": "Teacher"
}
];
上面的代碼總是給出以下輸出:
**These are my names....
IP0 with type of Student and color Red
IPwd1 with type of Student and color Red
IPed3 with type of Student and color Red
IP4ed with type of Student and color Red**
我希望 HTML 僅對前 2 個學生運行。
似乎 'x' 在執行下一個回圈時總是初始化為 1 或不遞增。我怎樣才能讓它有條件地運行一些迭代?有任何想法嗎?
圖片
uj5u.com熱心網友回復:
這是一個“正確”的方法,盡管在這個例子中有點矯枉過正。您應該在 ng-repeat 串列上使用過濾器,而不是操作原始資料源。要將結果限制為某個 #,請使用limitTo. 在下面的示例中,過濾器是可擴展的。你可以做到filterBy:{type:'Student', color:'Red'}等
html:
<div ng-repeat="a in data.result | filterBy:{type:'Student'} | limitTo:2">
{{::a.name}} with type of {{::a.type}} and color {{::a.color}}
</div>
角度過濾器
app.filter('filterBy', function() {
return function(data, filters) {
return data.filter(d => {
let ret = true, x;
for(x in filters) {
if (d[x]!=filters[x]) ret = false;
}
return ret;
})
};
})
查看 Plnkr:
https://plnkr.co/edit/g72UNjTgQUtofKqo?open=lib/script.js&deferRun=1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/366877.html
標籤:javascript html angularjs 立即服务
