Search code examples
angularjspluralizeangularjs-ng-pluralize

ng-pluralize hide element when value is 0 (zero)


I would like to user Angulars ng-pluralize to hide/show/change an element in such way that of the value is 0, the element should be hidden (as in ng-hide="value == 0" or ng-if="value != 0").

When the value is 1, the element should have one text, and if it's more than 1 it should have one text. The value can never be negative. That's why I want to use ng-pluralize.

My question is; can you use ng-pluralize to do this without having to put the element inside another element just for this?


Solution

  • Use a combination of ng-hide and ng-pluralize within the same element

    var module = angular.module('myApp', []);
    module.controller('mainController', function($scope) {
      //$scope.personCount = 0;
      $scope.personCount = 1;
      //$scope.personCount = 2;
    });
    .myEl {
      background-color: grey;
      width: 100%;
      height: 25px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="myApp" ng-controller="mainController">
      <ng-pluralize ng-if="personCount > 0" class="myEl" count="personCount" when="{'0': 'Nobody is viewing.',
                         'one': '1 person is viewing.',
                         'other': '{} people are viewing.'}">
      </ng-pluralize>
    </div>