Search code examples
javascriptangularjsangular-ng-ifangularjs-ng-if

Count ng-if true statements in angularjs?


I have a page which shows different data with ng-ifs, I need to show how many of them are true on the same page. Just the number. The HTML is complex, but I have made a simpler version to understand how things work. Here is what the HTML looks like, and the data is being manipulated on the page as well, so the ng-if value can change after it has been rendered and hence the count on the page should be changing with it.

<div ng-if="abc">
  some data 1 
</div>
<div ng-if="!abc">
  some data 2
</div>
<div ng-if="xyz">
  some data 3
</div>
<div ng-if="abc">
  some data 4
</div>
<div ng-if="!xyz">
  some data 5
</div>

I made a plnkr as well. http://plnkr.co/edit/5wdiSLhbHpOPJGjRn47L?p=preview

Thank you.


Solution

  • A pure JavaScript solution could be to add a class (or an attribute) to the HTML elements which have ng-if conditions, and then use document.getElementsByClassName('class-name').length to get the number of elements which have the ng-if condition true.

    Example:

    <div class="sample-class" ng-if="abc">
      some data 1 
    </div>
    <div class="sample-class" ng-if="!abc">
      some data 2
    </div>
    <div class="sample-class" ng-if="xyz">
      some data 3
    </div>
    <div class="sample-class" ng-if="abc">
      some data 4
    </div>
    <div class="sample-class" ng-if="!xyz">
      some data 5
    </div>
    
    <div>Total count is: {{getCount(); totalCount}}</div>
    
    <script type="text/javascript">
        angular.module('app', [])
        .controller('ctrl', function($scope, $timeout) {
            $scope.totalCount = 0;
            $scope.getCount = function(){
                $timeout(function(){
                    $scope.totalCount = document.getElementsByClassName('sample-class').length;
                });
            };  
        }); 
    </script>