Rookie Rookie - 10 days ago 7
AngularJS Question

Display a count of SELECT element which has a valid value selected using AngularJS

I have 3 select dropdown box and a label. I need to display the count of Select box which have value in it and need recalculate the count whenever user reset(select empty entry) or select the value of dropdown box using

AngularJS
.

How to do this in
AngularJS
?

Answer

Simply you can have a method in the span to check the models and return the count as below.

You can have an object to hold all the selected values.

var app = angular.module('app', []);

app.controller('TestController', function($scope) {
   $scope.models = {};
   
   $scope.count = function() {
     var count = 0;
     
     angular.forEach($scope.models, function(val, key) {
       if(val) ++count;
     });
     
     return count;
   };
});


angular.bootstrap(document, ['app']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="TestController">
  <select ng-model="models.model1">
    <option value=""></option>
    <option value="0">Option 1</option>
    <option value="1">Option 2</option>
    <option value="2">Option 3</option>
  </select>
  <select ng-model="models.model2">
    <option value=""></option>
    <option value="0">Option 1</option>
    <option value="1">Option 2</option>
    <option value="2">Option 3</option>
  </select>
  <select ng-model="models.model3">
    <option value=""></option>
    <option value="0">Option 1</option>
    <option value="1">Option 2</option>
    <option value="2">Option 3</option>
  </select>
  <p>
    <span>{{count()}}</span>
  </p>
</div>