change selected item in md-select programatically

2019-07-14 11:30发布

问题:

I want to initially (on page load) set the current schoolclass item in the md-select.

This code sets the selected schoolclass but it is not reflected in the md-select visually.

$scope.selectedSchoolclass = schoolclasses.length > 0 ? schoolclasses[0] : null;

<md-input-container>
    <label>Schoolclasses</label>
    <md-select ng-model="selectedSchoolclass"  md-on-close="getPupils()">
        <md-option ng-repeat="s in schoolclasses" ng-value="{{s}}">
            {{s.schoolclassNumber}}
        </md-option>
    </md-select>
</md-input-container>

When I use md-selected="$first" then it is selected visually in the md-select but I get an error from a computed property which seem to evaluate first just before the $first. Thus I cannot set the first schoolclass as the selected schoolclass from html. I have to do it via JS in the controller.

How can I do that?

回答1:

You were close. Just change

<md-option ng-repeat="s in schoolclasses" ng-value="{{s}}">

To

<md-option ng-repeat="s in schoolclasses" ng-value="s">

ng-value is already expecting an angular expression (see here), so you don't need to evaluate the expression with {{}}.

EDIT:

And also, I assume you meant:

$scope.selectedSchoolclass = $scope.schoolclasses.length > 0 ? $scope.schoolclasses[0] : null;

schoolclasses needs to be $scope.schoolclasses because you reference it in your template.



回答2:

You probably need to add ng-model-options and specify the trackBy on some identifying property - id, name or schoolclassNumber probably.

Also, as make sure to remove the {{}} on ng-value.

<md-select ng-model="selectedSchoolclass"  md-on-close="getPupils()" ng-model-options="{trackBy: '$value.schoolclassNumber'}">
    <md-option ng-repeat="s in schoolclasses" ng-value="s" ng-bind="s.schoolclassNumber"></md-option>
</md-select>

I am also not sure if assigning null can be a problem here, maybe try undefined.

It is also good practice to specify a track by on the ng-repeat. Again, use your identifying property.

<md-option ng-repeat="s in schoolclasses track by s.schoolclassNumber" ng-value="s" ng-bind="s.schoolclassNumber"></md-option>


回答3:

Just change your md-select like this

  <md-select ng-model="selectedSchoolclass"  md-on-close="getPupils()">
        <md-option ng-repeat="s in schoolclasses" ng-value="{{s}}">
            {{s.schoolclassNumber}} ng-selected="{{ selectedSchoolclass.indexOf(s.schoolclassNumber) > -1}}"
        </md-option>
    </md-select>