Avi
Avi

Reputation: 21866

Programmatically select an md-select option

I have an angular-material md-select element with multiple selection which I define like this:

<md-select ng-model="selectedTypes"
           ng-change="typesChanged()"
           multiple
           ng-disabled="availableTypes.length == 0">
           <md-option ng-repeat="type in availableTypes" ng-value="{{type}}">
              {{type.displayName}}
           </md-option>
</md-select>

During the load of the controller I load an array of available types from the server and then set the selectedTypes to availableTypes[0] (after the availableTypes is loaded) as follows:

$scope.promise = Types.query(query, function (types) { // Types is a $resource
        $scope.availableTypes = types;
        $scope.selectedTypes = [$scope.availableTypes[0]];
});

Because selectedTypes is the model of the md-select directive, I expected that it will make the first selection option become selected. But it didn't work. I couldn't find in the documentation any way to programmatically select an element in the md-select.

Upvotes: 2

Views: 2872

Answers (1)

nextt1
nextt1

Reputation: 3988

Since you are using md-select with multiple then model you bind to md-select must be an array and you defined in your code like this.

$scope.selectedTypes = [$scope.availableTypes[0]];

which doesn't represent a array. You just need to add the value you specify in you md-option to that model.

$scope.selectedTypes = []; //defined array
$scope.selectedTypes.push($scope.availableTypes[0]);

Check out following pen for working example.

http://codepen.io/next1/pen/qZKzMy

In you code you used ng-value="{{type}}. Since ng-value is angular directive you should not use {{ }}. Check out the offical Doc about ngValue

Upvotes: 1

Related Questions