繁体   English   中英

选择/选项ng-model未与ng-selected绑定

[英]select/options ng-model is not bound with ng-selected

的jsfiddle

我有这个AngularJS html用于选择/选项,默认情况下是根据外部值(selectedGroup)选择的。 此列表应该有一个空选项(“ -ROOT-”选项):

<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>

问题是:当ng-selected条件导致一个选项被选中时,ng-model不受此选择的影响,但是当您更改选项时,ng-model将获得该值。 如何让ng-model的值直接采用自动选择的选项?

您应该使用ngOptions ngOptions旨在使用作为属性传递的微语法来填充选择输入。

例如,您可以使用以下方法:

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

这会列出每个groupgroups使用group.id作为值并显示group.name作为名称。 它为您处理更改检测。

您唯一需要做的就是考虑这一要求:

此列表应该有一个空选项(“ -ROOT-”选项):

我通过在groups数组的前面添加另一个选项来完成此操作:

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

最后,为了确保在初始化范围时选择了真实的东西,此行设置了newDoor.groupId

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

在这里查看更新的小提琴

您可以在控制器中实现此目的,方法是先将其预定义为新对象,然后在为selectedGroup放置值时放置值。

码:

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;
}

工作小提琴

要么

在html中有一个ng-init,其余的代码保持不变。

<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>

更新小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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