Dynamically creating multiselect Dropdown in AngularJs
<p>Hi i have one multiselect dropdown in angular which invokes directive. I want to create 5 dropdown which will refer same directive and controller, but for each dropdown there will be different action method in MVC. Your help can save my life</p>

<h2>Controller</h2>

<pre><code>var myApp = angular.module('myModule', ['angularjs-dropdown-multiselect']);
myApp.controller('multiselect', ['$scope', '$http', function ($scope, $http) {
    $scope.lobsSelected = [];
    $scope.lobs = [];
    $scope.dropdownSetting = {
        scrollable: true,
        scrollableHeight: '200px'
    }


    $http.get('Home/GetALLLOB').then(function (data) {
        angular.forEach(data.data, function (value, index) {
            $scope.lobs.push({ id: value.N_LevelID, label: value.T_LevelName }
            );
        });
    })
}])
</code></pre>

<h2>Directive</h2>

<pre><code>'use strict';

var directiveModule = angular.module('angularjs-dropdown-multiselect', []);



directiveModule.directive('ngDropdownMultiselect', ['$filter', '$document', '$compile', '$parse',
    function ($filter, $document, $compile, $parse) {

        return {
            //restrict: 'AE',
            restrict: 'AEC',
            scope: {
                selectedModel: '=',
                options: '=',
                extraSettings: '=',
                events: '=',
                searchFilter: '=?',
                translationTexts: '=',
                groupBy: '@',
                fn_selectAll: '&amp;',
            },

            template: fn_Template,
            link: function ($scope, $element, $attrs) {
                var $dropdownTrigger = $element.children()[0];

                $scope.toggleDropdown = function () {
                    $scope.open = !$scope.open;
                };

                $scope.checkboxClick = function ($event, id) {

                    $scope.setSelectedItem(id);
                    //var obj = getPropertyForObject(option, settings.idProp);

                    $event.stopImmediatePropagation();
                };

                $scope.externalEvents = {
                    onItemSelect: angular.noop,
                    onItemDeselect: angular.noop,
                    onSelectAll: angular.noop,
                    onDeselectAll: angular.noop,
                    onInitDone: angular.noop,
                    onMaxSelectionReached: angular.noop
                };

                $scope.settings = {
                    dynamicTitle: true,
                    scrollable: false,
                    scrollableHeight: '300px',
                    closeOnBlur: true,
                    displayProp: 'label',
                    idProp: 'id',
                    externalIdProp: 'id',
                    enableSearch: false,
                    selectionLimit: 0,
                    showCheckAll: true,
                    showUncheckAll: true,
                    closeOnSelect: false,
                    buttonClasses: 'btn btn-default',
                    closeOnDeselect: false,
                    groupBy: $attrs.groupBy || undefined,
                    groupByTextProvider: null,
                    smartButtonMaxItems: 0,
                    smartButtonTextConverter: angular.noop
                };

                $scope.texts = {
                    checkAll: 'Check All',
                    uncheckAll: 'Uncheck All',
                    selectionCount: 'checked',
                    selectionOf: '/',
                    searchPlaceholder: 'Search...',
                    buttonDefaultText: 'LOB',
                    dynamicButtonTextSuffix: 'Selected',
                    LOBSelected: ''
                };

                $scope.searchFilter = $scope.searchFilter || '';

                if (angular.isDefined($scope.settings.groupBy)) {
                    $scope.$watch('options', function (newValue) {
                        if (angular.isDefined(newValue)) {
                            $scope.orderedItems = $filter('orderBy')(newValue, $scope.settings.groupBy);
                        }
                    });
                }

                angular.extend($scope.settings, $scope.extraSettings || []);
                angular.extend($scope.externalEvents, $scope.events || []);
                angular.extend($scope.texts, $scope.translationTexts);

                $scope.singleSelection = $scope.settings.selectionLimit === 1;

                function getFindObj(id) {
                    var findObj = {};

                    if ($scope.settings.externalIdProp === '') {
                        findObj[$scope.settings.idProp] = id;
                    } else {
                        findObj[$scope.settings.externalIdProp] = id;
                    }

                    return findObj;
                }

                function clearObject(object) {
                    for (var prop in object) {
                        delete object[prop];
                    }
                }

                if ($scope.singleSelection) {
                    if (angular.isArray($scope.selectedModel) &amp;&amp; $scope.selectedModel.length === 0) {
                        clearObject($scope.selectedModel);
                    }
                }

                if ($scope.settings.closeOnBlur) {
                    $document.on('click', function (e) {
                        var target = e.target.parentElement;
                        var parentFound = false;

                        while (angular.isDefined(target) &amp;&amp; target !== null &amp;&amp; !parentFound) {
                            if (_.contains(target.className.split(' '), 'multiselect-parent') &amp;&amp; !parentFound) {
                                if (target === $dropdownTrigger) {
                                    parentFound = true;
                                }
                            }
                            target = target.parentElement;
                        }

                        if (!parentFound) {
                            $scope.$apply(function () {
                                $scope.open = false;
                            });
                        }
                    });
                }

                $scope.getGroupTitle = function (groupValue) {
                    if ($scope.settings.groupByTextProvider !== null) {
                        return $scope.settings.groupByTextProvider(groupValue);
                    }

                    return groupValue;
                };

                $scope.getButtonText = function () {

                    if ($scope.settings.dynamicTitle &amp;&amp; ($scope.selectedModel.length &gt; 0 || (angular.isObject($scope.selectedModel) &amp;&amp; _.keys($scope.selectedModel).length &gt; 0))) {

                        //if ($scope.settings.smartButtonMaxItems &gt; 0) {

                        if ($scope.settings.smartButtonMaxItems &gt;= 0) {


                            var itemsText = [];
                            var SelectedTexts = [];

                            angular.forEach($scope.options, function (optionItem) {

                                if ($scope.isChecked($scope.getPropertyForObject(optionItem, $scope.settings.idProp))) {
                                    var displayText = $scope.getPropertyForObject(optionItem, $scope.settings.displayProp);

                                    $scope.SelectedTexts = displayText;
                                    var converterResponse = $scope.settings.smartButtonTextConverter(displayText, optionItem);

                                    itemsText.push(converterResponse ? converterResponse : displayText);
                                }
                            });

                            //if ($scope.selectedModel.length &gt; $scope.settings.smartButtonMaxItems) {
                            //    itemsText = itemsText.slice(0, $scope.settings.smartButtonMaxItems);
                            //    itemsText.push('...');
                            //}

                            if (itemsText.length &lt;= 2) {
                                return itemsText.join(', ');
                            }

                            else {
                                var totalSelected;

                                if ($scope.singleSelection) {
                                    totalSelected = ($scope.selectedModel !== null &amp;&amp; angular.isDefined($scope.selectedModel[$scope.settings.idProp])) ? 1 : 0;
                                } else {
                                    totalSelected = angular.isDefined($scope.selectedModel) ? $scope.selectedModel.length : 0;
                                }

                                if (totalSelected === 0) {
                                    return $scope.texts.buttonDefaultText;
                                } else {


                                    return totalSelected + ' ' + $scope.texts.buttonDefaultText + ' ' + $scope.texts.dynamicButtonTextSuffix;

                                }
                            }

                        }
                    } else {
                        return $scope.texts.buttonDefaultText;
                    }
                };

                $scope.getPropertyForObject = function (object, property) {
                    if (angular.isDefined(object) &amp;&amp; object.hasOwnProperty(property)) {
                        return object[property];
                    }

                    return '';
                };

                $scope.selectAll = function () {
                    debugger;
                    $scope.deselectAll(false);
                    $scope.externalEvents.onSelectAll();

                    angular.forEach($scope.options, function (value) {
                        $scope.setSelectedItem(value[$scope.settings.idProp], true);
                    });
                };

                $scope.deselectAll = function (sendEvent) {
                    sendEvent = sendEvent || true;

                    if (sendEvent) {
                        $scope.externalEvents.onDeselectAll();
                    }

                    if ($scope.singleSelection) {
                        clearObject($scope.selectedModel);
                    } else {
                        $scope.selectedModel.splice(0, $scope.selectedModel.length);
                    }
                };

                $scope.setSelectedItem = function (id, dontRemove) {
                    var findObj = getFindObj(id);
                    var finalObj = null;

                    if ($scope.settings.externalIdProp === '') {
                        finalObj = _.find($scope.options, findObj);
                    } else {
                        finalObj = findObj;
                    }

                    if ($scope.singleSelection) {
                        clearObject($scope.selectedModel);
                        angular.extend($scope.selectedModel, finalObj);
                        $scope.externalEvents.onItemSelect(finalObj);
                        if ($scope.settings.closeOnSelect) $scope.open = false;

                        return;
                    }

                    dontRemove = dontRemove || false;

                    var exists = _.findIndex($scope.selectedModel, findObj) !== -1;



                    if (!dontRemove &amp;&amp; exists) {
                        $scope.selectedModel.splice(_.findIndex($scope.selectedModel, findObj), 1);
                        $scope.externalEvents.onItemDeselect(findObj);
                    } else if (!exists &amp;&amp; ($scope.settings.selectionLimit === 0 || $scope.selectedModel.length &lt; $scope.settings.selectionLimit)) {
                        $scope.selectedModel.push(finalObj);
                        $scope.externalEvents.onItemSelect(finalObj);
                    }
                    if ($scope.settings.closeOnSelect) $scope.open = false;
                };

                $scope.isChecked = function (id) {
                    if ($scope.singleSelection) {
                        return $scope.selectedModel !== null &amp;&amp; angular.isDefined($scope.selectedModel[$scope.settings.idProp]) &amp;&amp; $scope.selectedModel[$scope.settings.idProp] === getFindObj(id)[$scope.settings.idProp];
                    }

                    return _.findIndex($scope.selectedModel, getFindObj(id)) !== -1;
                };

                $scope.externalEvents.onInitDone();

            }





        };
    }]);





function fn_Template(element, attrs) {



    var checkboxes = attrs.checkboxes ? true : false;
    var groups = attrs.groupBy ? true : false;


    var template = '&lt;div class="multiselect-parent btn-group dropdown-multiselect"&gt;';
    template += '&lt;button type="button" class="dropdown-toggle" ng-class="settings.buttonClasses" ng-click="toggleDropdown()"&gt;{{getButtonText()}}&amp;nbsp;&lt;span class="caret"&gt;&lt;/span&gt;&lt;/button&gt;';
    template += '&lt;ul class="dropdown-menu dropdown-menu-form" ng-style="{display: open ? \'block\' : \'none\', height : settings.scrollable ? settings.scrollableHeight : \'auto\' }" style="overflow: scroll" &gt;';
    template += '&lt;li ng-hide="!settings.showCheckAll || settings.selectionLimit &gt; 0"&gt;&lt;a data-ng-click="selectAll()"&gt;&lt;span class="glyphicon glyphicon-ok"&gt;&lt;/span&gt;  {{texts.checkAll}}&lt;/a&gt;';
    template += '&lt;li ng-show="settings.showUncheckAll"&gt;&lt;a data-ng-click="deselectAll();"&gt;&lt;span class="glyphicon glyphicon-remove"&gt;&lt;/span&gt;   {{texts.uncheckAll}}&lt;/a&gt;&lt;/li&gt;';
    template += '&lt;li ng-hide="(!settings.showCheckAll || settings.selectionLimit &gt; 0) &amp;&amp; !settings.showUncheckAll" class="divider"&gt;&lt;/li&gt;';
    template += '&lt;li ng-show="settings.enableSearch"&gt;&lt;div class="dropdown-header"&gt;&lt;input type="text" class="form-control" style="width: 100%;" ng-model="searchFilter" placeholder="{{texts.searchPlaceholder}}" /&gt;&lt;/li&gt;';
    template += '&lt;li ng-show="settings.enableSearch" class="divider"&gt;&lt;/li&gt;';

    if (groups) {
        template += '&lt;li ng-repeat-start="option in orderedItems | filter: searchFilter" ng-show="getPropertyForObject(option, settings.groupBy) !== getPropertyForObject(orderedItems[$index - 1], settings.groupBy)" role="presentation" class="dropdown-header"&gt;{{ getGroupTitle(getPropertyForObject(option, settings.groupBy)) }}&lt;/li&gt;';
        template += '&lt;li ng-repeat-end role="presentation"&gt;';
    } else {
        template += '&lt;li role="presentation" ng-repeat="option in options | filter: searchFilter"&gt;';
    }


    template += '&lt;a role="menuitem" tabindex="-1" ng-click="setSelectedItem(getPropertyForObject(option,settings.idProp))"&gt;';

    if (checkboxes) {
        template += '&lt;div class="checkbox"&gt;&lt;label&gt;&lt;input class="checkboxInput" type="checkbox" ng-click="checkboxClick($event, getPropertyForObject(option,settings.idProp))" ng-checked="isChecked(getPropertyForObject(option,settings.idProp))" /&gt; {{getPropertyForObject(option, settings.displayProp)}}&lt;/label&gt;&lt;/div&gt;&lt;/a&gt;';
    } else {
        template += '&lt;span data-ng-class="{\'glyphicon glyphicon-ok\': isChecked(getPropertyForObject(option,settings.idProp))}"&gt;&lt;/span&gt; {{getPropertyForObject(option, settings.displayProp)}}&lt;/a&gt;';
    }

    template += '&lt;/li&gt;';

    template += '&lt;li class="divider" ng-show="settings.selectionLimit &gt; 1"&gt;&lt;/li&gt;';
    template += '&lt;li role="presentation" ng-show="settings.selectionLimit &gt; 1"&gt;&lt;a role="menuitem"&gt;{{selectedModel.length}} {{texts.selectionOf}} {{settings.selectionLimit}} {{texts.selectionCount}}&lt;/a&gt;&lt;/li&gt;';

    template += '&lt;/ul&gt;';
    template += '&lt;/div&gt;';

    element.html(template);
}
</code></pre>

<h2>UI</h2>

<pre><code>&lt;div ng-app="myModule" ng-controller="multiselect"&gt;
    &lt;div ng-dropdown-multiselect="" extra-settings="dropdownSetting" options="lobs"
         selected-model="lobsSelected" checkboxes="true"&gt;
    &lt;/div&gt;
&lt;/div&gt;
</code></pre>

<h2>Action Method n MVC Controller</h2>

<pre><code>public JsonResult GetALLLOB()
        {
            iMetricsEntities dbContext = new iMetricsEntities();
            return new JsonResult
            {
                Data = dbContext.Levels.Where(objlevel =&gt; objlevel.N_ParentID == 0 &amp;&amp; objlevel.B_Active &amp;&amp; objlevel.N_LevelTypeID == 4),
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
</code></pre>

<p>if i create another div with same controller,directive it does not create 2nd dropdown. doing this it disturbs first dropdown as well...</p>