简体   繁体   中英

select/options ng-model is not bound with ng-selected

JSFiddle

I have this AngularJS html for a select/options with a selected item by default according to an external value (selectedGroup). There should be an empty option for this list ('-ROOT-' option):

<select class="form-control" ng-model="newDoor.groupId">
    <option value="">-ROOT-</option>
    <option ng-repeat="group in groups" ng-value="group.id" ng-selected="group==selectedGroup">
        {{group.name}}
    </option>
</select>

The problem is: when ng-selected condition causes an option to be selected, the ng-model is not affected by this select, but when u change the option, ng-model get the value. How to let the value of ng-model take the auto selected option directly?

You should use ngOptions . ngOptions is designed to populate select inputs, using a microsyntax passed as an attribute.

For example, in your case, you could use the following:

<select ng-model="newDoor.groupId" 
        ng-options="group.id as group.name for group in groups">

This would list every group in groups using group.id as the value and displaying group.name as the name. It handles the change detection for you.

The only extra thing you would need to do, is account for this requirement:

There should be an empty option for this list ('-ROOT-' option):

I have done this by adding another option to the front of your groups array:

$scope.groups.unshift({ name: '-ROOT-', id: -1 });

Finally, to make sure something real is selected when the scope initialises, this line sets newDoor.groupId :

$scope.newDoor = { groupId: $scope.groups[0].id }

See an updated fiddle here

You can achieve this in the controller by predefining it first as a new object and then putting the value when you putting the value for selectedGroup.

Code:

function doorsTreeController($scope) {
    $scope.newDoor = {};
    $scope.groups = [{
        name: 'G1',
        id: 1
    }, {
        name: 'G2',
        id: 2
    }, {
        name: 'G3',
        id: 3
    }, {
        name: 'G4',
        id: 4
    }];
    $scope.selectedGroup = $scope.groups[1];
    $scope.newDoor.groupId = $scope.selectedGroup.id;
}

Working Fiddle

OR

have a ng-init in html and rest of your code as is.

<div ng-app>
    <div ng-controller='doorsTreeController'>
        <select class="form-control" ng-init="newDoor.groupId = selectedGroup.id" ng-model="newDoor.groupId">
            <option value="">-ROOT-</option>
            <option ng-repeat="group in groups" ng-value="group.id" ng-selected="group==selectedGroup">{{group.name}}</option>
    </select>Selected groupId is: {{newDoor.groupId}}</div>

Updated Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM