AngularJs Multi Select Dropdown Options


AngularJs Multi Select Dropdown Options : We can use ng-model to create multi select dropdown. Here in this tutorial we are going to explain how you can create simple multi select dropdown using the Angular js ng-model. We will explain this with example and demo.


AngularJs Multi Select Dropdown Options Example

Let us have html and JavaScript part separately –

Html Part –

Here is Html Part for creating multi select dropdown in angularjs.

AngularJs Multi Select Dropdown Options Example:

<div ng-app="myApp">  
<div ng-controller="myController">  
 <label>Select Items:</label><br>
    <select multiple ng-model="selectedItems">
        <option value="1">Item 1</option>
        <option value="2">Item 2</option>
        <option value="3">Item 3</option>
        <option value="4">Item 4</option>
    </select>
	<p>
    <tt> selectedItems = {{selectedItems}}</tt>
	</p>
</div>  
</div> 

JavaScript Part –

Now Let us create javascript controller part.

AngularJs Multi Select Dropdown Options Example:

<script>
var myApp = angular.module("myApp", []);
 myApp.controller("myController", function($scope) {
 $scope.selected = [
        {id:1, name:"Item 1"}
    ];
    
    $scope.selectedItems = [];
    
    $scope.$watch('selected', function(nowSelected){
        $scope.selectedItems = [];
        
        if( ! nowSelected ){
		    // if not selected then return
            return;
        }
        angular.forEach(nowSelected, function(val){
            $scope.selectedItems.push( val.id.toString() );
        });
    });

});
</script> 

Try it »

In this example we have created a ng-model selectedItems to perform the muli select action. We have assigned the Item1 as default selected. $scope.selected is used to set the deault selected items. If you run the above example it will produce output something like this –

AngularJs Multi Select Dropdown Options


Advertisements

Add Comment

📖 Read More