Search code examples
javascriptangularjsangularjs-scope

angularjs - select's ng-model index


I am trying to get all the selected item(s), e.g its value or title, in a select control. Basically, after user has selected the item(s) he/she wants from the select control, I want to get the number of selected items and its title or value.

In my html page, I have the following code snippet:

  <select ng-model="selectedValues" multiple>
            <option >All Booth</option>
            <option> Washroom</option>    
 </select>

 <button ng-click="apply()" type="button">Apply</button>

In my controller, I have the following code snippet:

$scope.apply = function () {
// Get the number of selected items and its title or value


}

Does anyone know a way I could achieve this? Thanks.


Solution

  • Please check demo:

    angular.module('app', [])
    
    .controller('appCtrl', function ($scope) {
    
        $scope.apply = function () {
            if ($scope.selectedValues != undefined && $scope.selectedValues.length > 0) {
                // Get the number of selected items and its title or value
                var selectedTitles = $scope.selectedValues;//Get title or value
                var noSelectedItems = $scope.selectedValues.length;//Get the number of selected items
    
                console.log("Total items selected :" + noSelectedItems + " titles '" + selectedTitles.toString() + "'");
            }
            else {
                console.log("No item selected");
            }
        }
    
    });
    <!DOCTYPE html>
    <html>
    
      <head>
        
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
       
      </head>
    
      <body ng-app="app" ng-controller="appCtrl">
         <select ng-model="selectedValues" multiple>
                <option>All Booth</option>
                <option>Washroom</option>    
     </select>
    
     <button ng-click="apply()" type="button">Apply</button>
      </body>
    
    </html>