我试图执行以下操作:
当用户选择一个家庭时,在第二个下拉菜单中自动选择父母的姓名
当控制器设置对象时(例如,在模型更新表单的情况下),两个下拉列表应反映此对象:系列和父级应自动选择。
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>
问题:设置新的系列模型时,绑定效果不佳。
答案 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]