一个对象,两个选择下拉列表,ng-options和值绑定

时间:2015-07-07 09:27:40

标签: javascript angularjs angular-ngmodel ng-options

我试图执行以下操作:

  • 当用户选择一个家庭时,在第二个下拉菜单中自动选择父母的姓名

  • 当控制器设置对象时(例如,在模型更新表单的情况下),两个下拉列表应反映此对象:系列和父级应自动选择

See this example on Codepen

angular.module('app', []).controller('mainCtrl', function($scope) {
    $scope.families = [
        { name: "My first family", parent: "Parent #1" },
        { name: "My second family", parent: "Parent #2" },
        { name: "My third family", parent: "Parent #1" }
    ];

    $scope.importNew = function() {
        $scope.model = { name: "My third family", parent: "Parent #1" };
        $scope.message = "Problem: ^ the family name isn't bind, only the parent!";
    }

    $scope.importRef = function() {
        $scope.model = $scope.families[2];
        $scope.message = "It works!";
    }
});
<div ng-app="app" ng-controller="mainCtrl">
    <h1>ng-options model binding</h1>
    <select ng-options="fam.name group by fam.parent for fam in families"
            ng-model="model">
        <option disabled value="">— Choose —</option>
    </select>
    <select ng-options="fam.parent as fam.parent for fam in families"
            ng-model="model.parent">
        <option disabled value="">— Choose —</option>
    </select>
    <button ng-click="importNew()">Import a family (new family object)</button>
    <button ng-click="importRef()">Import a family (referenced family object)</button>
    <p><small>{{ message }}</small></p>

    <p>
        <strong>$scope.model :</strong>
        <pre>{{ model | json }}</pre>
    </p>

    <p>
        <strong>$scope.families :</strong>
        <pre>{{ families | json }}</pre>
    </p>
</div>

问题:设置新的系列模型时,绑定效果不佳。

1 个答案:

答案 0 :(得分:0)

要使自动选择生效,该对象必须是从中选择下拉列表的数组的一部分

// Auto-select won't work: this is a new object, even if it is equal to an existing object in the list
$scope.model = { name: "My third family", parent: "Parent #1" }

// Auto-select will work: the object is directly one of the dropdowns' list
$scope.model = $scope.families[2]