我需要在现在选中的元素集合中放置一个标记selected = true。我做错了什么?
<div class="form-group">
<label for="sourseSelector">Sourses</label>
<select id="sourseSelector" class="form-control" ng-options="true as sourse.text for sourse in sourses" ng-model="sourse.selected"></select>
</div>
控制器中的代码
$scope.sourses = [
{name: "peoples", text: "", selected:false},
{name: "firms", text: "", selected:false},
{name: "clients", text: "", selected:false},
{name: "contracts", text: "", selected:false}
]
答案 0 :(得分:0)
最简单的方法是拥有一个单独的模型属性并将其分配给所选项并使用ng-model
绑定它:
$scope.sourses = [
{name: "peoples", text: "peoples"},
{name: "firms", text: "firms"},
{name: "clients", text: "clients"},
{name: "contracts", text: "contracts"}
];
这将选择第二个选项:
$scope.selectedSource = $scope.sourses[1];
查看:
<select id="sourseSelector" class="form-control" ng-options="sourse.text for sourse in sourses" ng-model="selectedSource"></select>
答案 1 :(得分:0)
在初始代码中,您尝试使用谓词(sourse.selected
)而不是控制器属性来选择字段的值。 ng-model
不允许这样做,这就是为什么它无法正常工作的原因。
要根据属性(如“已选择”)在选择框中设置默认值,请尝试将select的ng-model
指令分配给一个全新的属性,然后使用ng-init
将其设置为启动。要在每次更改选择框中的值时更新对象的selected
标记,请使用ngChange directive:
HTML:
<label for="sourseSelector">Sourses</label>
<select id="sourseSelector" class="form-control" ng-init="setDefault()" ng-options="sourse.name for sourse in sourses" ng-model="selectedSourse" ng-change="updateSelectedSourse()" >
JS:
$scope.sourses = [
{name: "peoples", text: "Ppl", selected:false},
{name: "firms", text: "Frm", selected:false},
{name: "clients", text: "Cli", selected:true},
{name: "contracts", text: "Con", selected:false}
];
$scope.setDefault = function() {
$scope.selectedSourse = $scope.sourses.filter(function(obj) { return !!obj.selected; })[0];
};
$scope.deselectAll = function(sources) {
sources.forEach(function(source) { source.selected = false; });
};
$scope.updateSelectedSourse() {
$scope.deselectAll($scope.sourses);
$scope.selectedSourse.selected = true;
};
这会抓取数组中第一个对象为true的对象,并将其设置为在启动时链接到选择字段$scope
的{{1}}属性。如果所有值都没有选定值“true”,则该字段将保持空白。当您更改所选值时,ng-model
将遍历您的所有课程,确保它们未被选中,然后将新选择的项目标记为所选项目。这一切都围绕您为updateSelectedSourse()
创建的selectedSourse
属性:每次选择新选项时,它都已经自动更新,您只需手动更新对象的数据。
这是一个现场演示@ jsFiddle:http://jsfiddle.net/HB7LU/15573/(已更新,包括ng-model
标记更改)