AngularJS directive for a multi-select

10,233

Based on Rashim's blog, this is what I tried in Plunke. https://rashimuddin.wordpress.com/2014/07/08/multi-select-drop-down-in-angularjs/

Check this out http://plnkr.co/edit/y8VOlgeSMOqHjFxoZU1L?p=previewenter code here

HTML

 <div dropdown-multiselect="" items="FirstItems" on-close="closeAlert(val)" on-Validation="addAlert(validationMsg)" max-Selection="3" selected-items="FirstSelectedItems"></div>

Angular directive would be

var app = angular.module('myApp', ['ui.bootstrap']);
app.controller('AppCtrl', ["$scope", function($scope) {

$scope.status = {
  isopen: false
};

$scope.FirstItems = [];

$scope.alerts = [{
  type: 'danger',
  msg: 'Oh snap! Change a few things up and try submitting again.'
}, {
  type: 'success',
  msg: 'Well done! You successfully read this important alert message.'
}];

$scope.addAlert = function(validationMsg) {
  if ($scope.validateFire === true) {
    $scope.alerts.push({
      msg: validationMsg
    });
  }
  $scope.validateFire = true;
};

$scope.closeAlert = function(val) {
  $scope.alerts = [];
}

for (var i = 0; i <= 20; i++) {
  var obj = [];
  obj["Id"] = i;
  obj["Name"] = "Name" + i;
  obj["IsSelected"] = false;
  $scope.FirstItems.push(obj);
}

$scope.FirstSelectedItems = [];

var removeItem = function(items, item) {
  for (var index = 0; index < items.length; index++) {
    if (item.Id == items[index].Id) {
      item.IsSelected = false;
      items.splice(index, 1);
      break;
    }
  }
};

$scope.removeFirstItem = function(item) {
  removeItem($scope.FirstSelectedItems, item);
};
$scope.removeSecondItem = function(item) {
  removeItem($scope.SecondSelectedItems, item);
};}]);

Directive goes like this

app.directive('dropdownMultiselect', function() { return { restrict: 'A', scope: { items: "=", selectedItems: "=", maxSelection: "=", validateFire: "=", onValidation: '&', onClose: '&' }, template: "" + "" + "Add " + "" + "" + "" + "" + "All " + "None" + "" + "

" + "" + "  " + "{{item.Name}}" + "" + "" + "", controller: function($scope) { $scope.handleClick = function($event) { $event.stopPropagation(); }; $scope.status = { isopen: false }; $scope.status = { isopen: false };

  $scope.openDropdown = function($event) {
    if ($scope.items !== undefined && $scope.items.length > 0) {

      if ($scope.items.length > $scope.maxSelection)
        $scope.showAll = false;
      else
        $scope.showAll = true;

      for (var index = 0; index < $scope.items.length; index++) {
        $scope.items[index].IsSelected = false;
      }
      if ($scope.selectedItems !== undefined && $scope.selectedItems.length > 0) {
        for (var selectedItemIndex = 0; selectedItemIndex < $scope.selectedItems.length; selectedItemIndex++) {
          for (var itemIndex = 0; itemIndex < $scope.items.length; itemIndex++) {
            if ($scope.selectedItems[selectedItemIndex].Id == $scope.items[itemIndex].Id) {
              $scope.items[itemIndex].IsSelected = true;
              break;
            }
          }
        }
      }
    }
    $event.stopPropagation();
    $scope.status.isopen = true;
  };

  $scope.selectAll = function($event) {
    $scope.selectedItems = [];
    angular.forEach($scope.items, function(item) {
      item.IsSelected = true;
      $scope.selectedItems.push(item);
    });
    $event.stopPropagation();
  };
  $scope.deselectAll = function($event) {
    angular.forEach($scope.items, function(item) {
      item.IsSelected = false;
    });
    $scope.selectedItems = [];
    $event.stopPropagation();
  };
  $scope.selectItem = function(item) {
    if (item.IsSelected === false) {
      for (var index = 0; index < $scope.selectedItems.length; index++) {
        if (item.Id == $scope.selectedItems[index].Id) {
          item.IsSelected = false;
          $scope.selectedItems.splice(index, 1);

          $scope.onClose({
            val: "1"
          });

          break;
        }
      }
    } else {
      if ($scope.selectedItems.length > $scope.maxSelection) {
        item.IsSelected = false;
        $scope.validationMsg = "MAX_REACHED";
        $scope.validateFire = true;
        $scope.onValidation({
          validationMsg: "Max_Reached"
        });
        return;
      }

      $scope.selectedItems.push(item);
    }
  };

  $scope.clickItem = function($event) {
    $event.stopPropagation();
  };

  $scope.closeDropDown = function() {
    $scope.status.isopen = false;
    $event.stopPropagation();
  };
}

}; });`

Share:
10,233

Related videos on Youtube

jakethecool1
Author by

jakethecool1

Updated on May 30, 2022

Comments

  • jakethecool1
    jakethecool1 almost 2 years

    I am having trouble populating my multi-select. I am using this version of the multi-select http://davidstutz.github.io/bootstrap-multiselect/

    I have looked at this stack overflow page (How can I use Bootstrap Multiselect Dropdown in AngularJS) but I am still having problems. I am trying to populate my multi-select with data that I grab from a database which gets stored in provData.

    Here is my html:

    <div class="col-sm-8">
        <select class="form-control" multiple ht-multi-select ng-model="patient.provid" ng-options="prov.id as prov.code for prov in provData">
            <option value="{{prov.id}}">{{prov.code}}</option>
        </select>
    </div>
    

    Here is my directive:

    templates.directive('htMultiSelect', function() {
    return {
      replace: true,
      require: 'ngModel',
      scope: {},
      link:function(scope, element, attrs) {
        console.log($(element));
        console.log('hit');
          // Below setup the dropdown:
    
          $(element).multiselect({
            enableClickableOptGroups: true
          });
    
          // Below maybe some additional setup
          scope.$watch(attrs.ngModel, function () {
           $(element).multiselect('refresh');
          });
      }
    };
    });
    

    My main issue is I can not populate my multi-select with data from provData and I can not get it to set the ng-model. Any help will be greatly appreciated.

    • Vlad Gurovich
      Vlad Gurovich about 9 years
      can u create a plunker with your example?
    • jw56578
      jw56578 about 9 years
      what is the point of the directive? also, the model is going to be the object from the array, not the id of that object. plnkr.co/edit/CPhENXYXP7csvW00up2I?p=preview
    • jakethecool1
      jakethecool1 about 9 years
      @jw56578 I guess what I want is a select box that has checkboxes in it. The select box needs to be dynamics so I can't just hardcode in some providers. So if I can get a select box that has checkboxes in it that all saves to an ng-model that way I can use it later, I'll be a happy man.
    • jw56578
      jw56578 about 9 years
      Do you have to use a <select> ? I would suggest you just use a div with a label and and a check box. Does this help? stackoverflow.com/questions/14514461/…
    • jakethecool1
      jakethecool1 about 9 years
      @jw56578 I would prefer it to be a select box because provData could be insanely large and I don't want to clutter the page.
    • jw56578
      jw56578 about 9 years
      you can easily add the same type of behavior yourself. that being having a scrollable space. does this make sense: jsfiddle.net/MitulP91/xEy9E/3
  • Sildoreth
    Sildoreth about 9 years
    Link-only answers are insufficient on stackoverflow. Links should be included to provided additional information on your answer, not to serve as the answer.