Javascript 在多次选择中更改时在ng选项中选择新值
我在我的.html页面中有一个下拉列表作为多选:Javascript 在多次选择中更改时在ng选项中选择新值,javascript,angularjs,select,multiple-select,Javascript,Angularjs,Select,Multiple Select,我在我的.html页面中有一个下拉列表作为多选: <select class="form-control" multiple ng-model="filter.types" ng-change="onChange()" ng-options="option for option in filterOptions.types"> {{option}} </select> 在这里,我想获得当
<select class="form-control"
multiple
ng-model="filter.types"
ng-change="onChange()"
ng-options="option for option in filterOptions.types">
{{option}}
</select>
在这里,我想获得当前项目被添加到选定的filter.types。
我怎样才能做到这一点
如果是单个select,我可以简单地将ng模型传递给onChange函数
<select class="form-control"
ng-model="filter.type"
ng-change="onChange(filter.type)"
ng-options="option for option in filterOptions.types">
{{option}}
{{option}}
但如何通过多重选择实现这一点
有什么想法吗?:)
如果添加的选项为“全部”,我想删除所有选定的元素。如果选择了“全部”选项,那么当我选择下一个项目时,我只需要删除“全部”选项
您可以查看angular的文档以获得此问题的答案
使用
ng change
无法实现这一点,因为您需要跟踪上次选择的选项。你必须$watch
你的过滤器。键入这是一个数组,然后根据新值和旧值你可以决定做什么
$scope.$watch('filter.types', function(newVal, oldVal) {
if (newVal.length > oldVal.length) { //Updating only on selecting
var lastSelectedOption = [];
lastSelectedOption = $scope.diff(newVal, oldVal);
if (lastSelectedOption[0] == 'All') {
var i = newVal.length;
while (i--) {
if (newVal[i] != 'All') {
newVal.splice(i, 1); //Deleting other options
}
}
} else if (newVal.indexOf('All') > -1) {
newVal.splice(newVal.indexOf('All'), 1); //Deleting 'All' option
}
}
});
为你的推荐人工作。祝你好运 到底是什么阻止了您选择模型?可以,但我想知道当前添加到所选选项数组中的元素。因为如果选择的选项是“All”,我想清空数组,只保留“All”选项。如果索引大于0,我可以搜索indexOf('all)并删除所有元素。但是,如果我选择了“全部”,并且我想选择一些不同的东西,那么它将不起作用。如果我知道当前添加的项目是“全部”,我可以删除所有。如果它是不同的,我可以删除“全部”选项。这将是对您的问题的一个很好的补充,我建议您在我使用辅助数组解决此问题并检查“全部”的索引是否已在所选选项中时,使用此信息对其进行编辑。但不是很好,我希望能找到更好的选择。谢谢!那真的很有用。使用观察者就可以做到这一点。
Plunker:- https://plnkr.co/edit/rhX9AiAhPfHXB2c2BUZF?p=preview
$scope.$watch('filter.types', function(newVal, oldVal) {
if (newVal.length > oldVal.length) { //Updating only on selecting
var lastSelectedOption = [];
lastSelectedOption = $scope.diff(newVal, oldVal);
if (lastSelectedOption[0] == 'All') {
var i = newVal.length;
while (i--) {
if (newVal[i] != 'All') {
newVal.splice(i, 1); //Deleting other options
}
}
} else if (newVal.indexOf('All') > -1) {
newVal.splice(newVal.indexOf('All'), 1); //Deleting 'All' option
}
}
});