2

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.

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks Aleross but I'm trying to avoid writing a controller for this specially since I think is should be handle by the presentation layer.
Ended up using the filter, works like a charm, thanks Aleross!
4

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.

4 Comments

Thanks Blesh but I'm trying to do it in the markup, if possible. Is there a way to do that?
Sorry Blesh but this didn't work. ended up using a filter as suggested by Aleross. thanks anyway!
It should have worked. Do you have a fiddle of it not working? (I don't particularly care about the SO points, I'm more interested in correctness)
Here is a demonstration of what I thought you were asking for. I feel the filter answer (while it works) is a bit contrived.

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.