J Castillo
J Castillo

Reputation: 3357

How to add a conditions to an expression in 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.

Upvotes: 2

Views: 8067

Answers (2)

Ben Lesh
Ben Lesh

Reputation: 108491

To do that you can just use a function on your $scope:

app.controller('MainCtrl', function($scope) {
    $scope.foo = function() {
        return $scope.searchResults.iTotalRecords > 0 ? $scope.searchResults.iTotalRecords : 0;
    };
});

And in your markup:

<span>{{foo()}}</span>

EDIT: The 100% markup way...

<span ng-show="searchResults.iTotalRecords > 0">{{searchResults.iTotalRecords}}</span>
<span ng-show="searchResults.iTotalRecords <= 0">0</span>

You might also want to check on ngSwitch and ngHide for more advanced cases like this.

Upvotes: 4

Alex Ross
Alex Ross

Reputation: 3839

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

Upvotes: 5

Related Questions