<!DOCTYPE html>
<html>

<head>
  <script data-require="jquery@2.2.0" data-semver="2.2.0" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" data-semver="3.3.6" data-require="bootstrap.js@3.3.6"></script>
  <link data-require="bootstrap-css@3.3.6" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
  <script data-require="angularjs@1.5.5" data-semver="1.5.5" src="https://code.angularjs.org/1.5.5/angular.js"></script>
  <script src="https://rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js"></script>
  <link rel="stylesheet" href="https://rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" />
  <link href="style.css" rel="stylesheet" />
  <script src="script.js"></script>
</head>

<body ng-controller="Controller" ng-app="bootstrapMultiselect">
  <select ng-model="selection" multiple="multiple" multi-select>
    <optgroup label="Vegetables">
      <option value="tomatoes">Tomatoes</option>
      <option value="mushrooms">Mushrooms</option>
      <option value="onions">Onions</option>
    </optgroup>
    <optgroup label="Other">
      <option value="cheese">Cheese</option>
      <option value="mozarella">Mozzarella</option>
      <option value="pepperoni">Pepperoni</option>
    </optgroup>
  </select>
  <button ng-click="alert()">Show selection</button>
</body>

</html>
// Code goes here

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

app.controller('Controller', ['$scope', '$window', function($scope, $window) {
  $scope.selection = ['tomatoes', 'mozarella'];
  
  $scope.alert = function() {
    $window.alert(JSON.stringify($scope.selection));
  };
}]);

app.directive('multiSelect', function() {

  function link(scope, element) {
    var options = {
      enableClickableOptGroups: true,
      onChange: function() {
        element.change();
      }
    };
    element.multiselect(options);
  }

  return {
    restrict: 'A',
    link: link
  };
});

app.config(['$provide', function($provide) {
  $provide.decorator('selectDirective', ['$delegate', function($delegate) {
    var directive = $delegate[0];

    directive.compile = function() {

      function post(scope, element, attrs, ctrls) {
        directive.link.post.apply(this, arguments);

        var ngModelController = ctrls[1];
        if (ngModelController && attrs.multiSelect !== null) {
          originalRender = ngModelController.$render;
          ngModelController.$render = function() {
            originalRender();
            element.multiselect('refresh');
          };
        }
      }

      return {
        pre: directive.link.pre,
        post: post
      };
    };

    return $delegate;
  }]);
}]);
/* Styles go here */