我有一个 ng-repeat 循环遍历我模型中的国家名称。在某些国家/地区名称上,我希望将它们缩写以减少字符串的长度,例如,我希望将“北爱尔兰”输出为“N”。爱尔兰'。
JSON 模型
[
{
"id": 1,
"name": "Italy",
},
{
"id": 2,
"name": "Northern Ireland",
},
{
"id": 3,
"name": "Poland",
}
]
我可以只更改模型中的名称,但我宁愿保持原样,因为我希望原始数据完整。只有在这个特定实例中,我才想将其缩写。
我应该使用 ng-repeat
过滤器吗?如果可以,怎么做?
如果没有,还有其他建议吗?
HTML
<md-grid-tile ng-repeat="nation in nationData">
<img src="img/{{nation.name}}.png">
<md-grid-tile-footer>
<h3>{{nation.name | uppercase}}</h3>
</md-grid-tile-footer>
</md-grid-tile>
最佳答案
您可以创建自己的过滤器 abbreviate
并将其应用于名称。在此过滤器中,您可以打开国家名称并返回缩写格式。
app.filter('abbreviate', function() {
return function(country) {
switch(country){
case "Northern Ireland":
country = "N. Ireland"
break;
}
return country;
}
});
关于javascript - 在 ng-repeat 上更改一次迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36452181/