Skip to content

AngularJS – set default multi select drop down value from controller

I am using AngularJS multi select drop down code from the following source: MultiSelectDropDown

I am using the same drop down twice in the same html page. I want to display the default selected drop down name of first multi select drop down as “Projects” and the second as “Environments”.

The code in the multiselect.js file is using a directive and scope.header is set to “Select” as default and i want to change the default name “Select” to “Projects” and “Environments” in my html page.

I need your help to update it either using multiselect syntax in html page or from the controller to pass the scope.header value.

Answer

Overview

The string value ‘Select’ is hardcoded into the directive. You will need to modify the code to make it dynamic.

Code

Here how I changed it.

https://plnkr.co/edit/J4CBblcfdDcrvE6K?preview

Index.html

I added the header attribute with the text I wanted it to show.

Lines 17-24

  <multiselect class="input-xlarge" multiple="true"
        ng-model="selectedCar"
        header="Cars"
        options="c.name for c in cars"
        change="selected()" ></multiselect>
        <div class="well well-small">
            {{selectedCar}}
        </div>

multiselect.js

I made the scope.header set to the attribute and default to ‘Select’ if nothing is given.

Line 45

scope.header = attrs.header || 'Select';

Line 119

if (!modelCtrl.$modelValue || !modelCtrl.$modelValue.length) return scope.header = attrs.header || 'Select';