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.

4

2 回答 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

于 2012-11-26T21:44:38.680 回答
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.

于 2012-11-26T21:17:11.693 回答