Angularjs – How to add a conditions to an expression in AngularJS

angularjs

I'm trying to do something in Angular like this:

Your search found {{ searchResults.iTotalRecords > 0 , 0 }} results.

Certainly this doesn't work but you get the idea. If my object is an integer, how can I check if the value is greater than zero or else set it to 0?

Thanks.

Best Answer

Custom Angular filters are well-suited for this purpose if you only want to change the presentation of the data, without changing the underlying (real) data in your application.

Below is an example filter for your use-case. You could put any other logic in your filter.

HTML:

<p>Your search found {{searchResults.iTotalRecords | resultCountFilter}} results.</p>

Javascript:

angular.module('app', []).filter('resultCountFilter', function () {
    return function (resultCount) {
        return resultCount > 0 ? resultCount : 0;          
    };
});​

Here's a JSFiddle: http://jsfiddle.net/alexross/ZN87E/

AngularJS Docs on Filters: Understanding Angular Filters