knowledge20
knowledge20

Reputation: 1436

Implementing multiselect dropdown in angular js

I am trying to implement a multiselect dropdown in AngularJS and trying to store the values in an list in my JS file. However I am unable to handle the event for selecting multiple values.

I have used ng-change but this handles only one click. Selecting multiple values using CTRL + arrow key is not handled. My list is dynamically generated.

Please suggest ways to handle it using Javascript/AngularJS

<div>
 <select multiple class="form-control drop-down" name="abclist" id="users"  ng-model="databaseUser" ng-options="databaseUser.username for databaseUser in databaseUsers" ng-change="ctrl.onchange()" required>
    <option value="" >SELECT USER VALUE</option>
  </select>
</div>
(function () {
  'use strict';

  angular.module(userdetails.module).controller('UserController', UserController);

  UserController.$inject = ['$scope', '$rootScope','$http', 'dData', '$location', '$uibModal'];
  function AdminController($scope, $rootScope, $http, dData, $location, $uibModal) {
    function onchange(){
  }

Upvotes: 2

Views: 8055

Answers (1)

You don't need to catch the onChange event to do that, the ng-model attribute will do the work for you.

HTML

<div ng-app="myModule">
  <div ng-controller="myController as ctrl">
    <div>
      <p>Selected users: {{ctrl.selectedUsers}}</p>
        <select multiple
                id="users"  
                ng-model="ctrl.selectedUsers" 
                ng-options="user as user.label for user in ctrl.users track by user.id">
        </select>
    </div>
  </div>
</div>

Javascript

var module = angular.module("myModule", []);

module.controller("myController", function() {
  var $ctrl = this;
  $ctrl.users = [{id:1, label:'eyp'}, {id:2, label:'jrt'}];
  $ctrl.selectedUsers = null;
});

Here you have a JSFiddle test to show you how it works.

Upvotes: 3

Related Questions