我有以下范围,如果这个范围大于5,我希望显示类似于'超过10个项目'否则它只会列出人类可读列表中的项目
<span class="bold-words">{{rule.words.join(', ')}}</span>
AngularJS的正确方法是什么?
例如,它会显示如下
// less than 5
Your list is "peas, fruit, tea"
// more than 5
Your list is greater than 5 items
答案 0 :(得分:1)
尝试这样的事情......
<span class="bold-words">Your list is {{(rule.words.length>5)?'greater than 5 item':(rule.words.join(', '))}}</span>
答案 1 :(得分:1)
您可以使用三元运算符
轻松完成<span class="bold-words">Your list is {{ rule.words.length > 5 ? 'greater than 5 items' : rule.words.join(', ') }}</span>
答案 2 :(得分:1)
我更喜欢像{{ rule.words | beautifier:5 }}
这样的过滤器。所以你可以在不同的情况下使用它,并可以随意修改你的输出。有关工作示例,请参阅代码段:
var app = angular.module('bar', []);
app.controller('foo', function($scope) {
$scope.bar = ['asdasd', 'egeg', 'hjgkj', 'adaa'];
});
app.filter('beautifier', function() {
return function(input, count) {
var output;
if (input.length > count) {
output = 'Your list is greater than ' + count +' items.';
} else {
output = 'Your list is "' + input.join('", "') + '"';
}
return output;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="bar">
<div ng-controller="foo">
<p>{{ bar | beautifier:5 }}</p>
<p>{{ bar | beautifier:3 }}</p>
</div>
</div>