0

I have the following scope and if this is greater than 5, I'd like to display something like 'more than ten items' otherwise it will just list the items in a human readable list

<span class="bold-words">{{rule.words.join(', ')}}</span>

What is the correct AngularJS way to do this?

e.g so it would show like below

// less than 5 
Your list is "peas, fruit, tea"
// more than 5
Your list is greater than 5 items
1

3 Answers 3

1

You can do it easily with ternary operator

<span class="bold-words">Your list is {{ rule.words.length > 5 ? 'greater than 5 items' : rule.words.join(', ') }}</span>
Sign up to request clarification or add additional context in comments.

Comments

1

try something like this ...

 <span class="bold-words">Your list is {{(rule.words.length>5)?'greater than 5 item':(rule.words.join(', '))}}</span>

Comments

1

I would prefer a filter like {{ rule.words | beautifier:5 }} So you can use it on different cases and can modify your output at will. See the snippet for a working example:

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.