Search code examples
angularjsangularjs-directiveangularjs-scope

How to count variables in Angular Js stub with value not NULL


this is my seperate stub file..

'requests': [
    {
        firstName: 'Richard',
        lastName: 'Love',
        purchase: '999999999',
        grant: 'Privlidge'
    },
    {
        firstName: 'Richard',
        lastName: 'Love',
        purchase: '999999999',
        grant: 'Block'
    },
    {
        firstName: 'Richard',
        lastName: 'Love',
        purchase: '999999999',
        grant: null

    }

I need to count number of requests with 'grant' value Not Null (! null), here it should return 2

this is the service which i am using to fetch record

  getRequestData: {
         method: 'GET',
         url: config.refrenceUrl + 'request-screen',
         isArray: false
     },

Please let me know if any more details are required.


Solution

  • You just have to loop over the array of request and count how many req['grant'] !== null are in the array (See snippet below and play around with the array of request in order to see how changes the grants not null)

    angular
      .module('app', [])
      .controller('myCtrl', function() {
    
        var vm = this;
    
        vm.wizard = {
          'requests': [{
              firstName: 'Richard',
              lastName: 'Love',
              purchase: '999999999',
              grant: 'Privlidge'
            },
            {
              firstName: 'Richard',
              lastName: 'Love',
              purchase: '999999999',
              grant: 'Block'
            },
            {
              firstName: 'Richard',
              lastName: 'Love',
              purchase: '999999999',
              grant: null
            }
          ],
          grantNotNullCount: fnGrantNotNullCount
        };
    
        return vm.wizard;
    
        function fnGrantNotNullCount() {
          var c = 0;
    
          angular.forEach(vm.wizard.requests, function(req) {
            if (req['grant'] !== null) {
              c++;
            }
          });
    
          return c;
        }
    
    
      });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <div ng-app="app" ng-controller="myCtrl as c">
    
      Requests
      <div ng-repeat="req in c.requests">
        <span>{{req}}</span><br/>
      </div>
     <br/>
      <strong>grants not null:</strong>
      <span ng-bind="c.grantNotNullCount()"></span>
      
    </div>