前端之家收集整理的这篇文章主要介绍了
AngularJS过滤多个选择输入,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_
403_0@
我真的很惊讶没有任何文档或关于AngularJS的这种更高级的过滤机制的问题 – 它对于任何UI都是必不可少的.
我需要过滤掉包含当前项目的选择选项.问题是当我们遍历进入过滤器的项目时,如何拼出每个选项,并为要过滤的列表中的每个选择返回正确的结果.
例如,如果我们有三个地区 – 加拿大,英国,美国 – 选择输入应如下所示:
Canada
[select]
[option0] United Kingdom
[option1] United States
United Kingdom
[select]
[option0] Canada
[option1] United States
United States
[select]
[option0] Canada
[option1] United Kingdom
.. 等等…
HTML:
<div ng-repeat="region in data.regions">
<h2> {{region.name}} </h2>
<input ui-select2="version2" type="hidden" name="keywordsLocal-{{$index}}" class="region-keywords input-xlarge" data-ng-model="data.regions[$index].keywords" required-multiple />
<select ui-select2 id="copy-{{$index}}" ng-show="region.length > 1" class="input-xlarge" ng-click="_copy($event,$index)" data-ng-model="data.regions[$index].keywords">
<option value="">Use the same keywords as:</option>
<option ng-repeat="region in data.regions | myFilter" value="{{region.keywords}}">{{region.name}}</option>
</select>
</div>
使用Javascript:
app.filter('myFilter',function() {
return function(items) {
var group = [];
for (var i = 0; i < items.length; i++) {
group.push(items.name);
}
for (var i = 0; i < group.length; i++) {
group[i].splice(i,1);
}
return group;
};
});
使选择不
包括当前选择的
内容存在缺陷.我将在
解决方案中包含
错误,以便您可以看到它.
ng-options是你需要的.以下是使用2个单独选择的示例.
<select ng-model='selectedCountry' ng-options='country.name for country in countries'></select>
<select ng-model='selectedCountry' ng-options='country.name for country in filteredCountries()'></select>
这是$scope件.请注意,filteredCountries只是返回国家/地区,减去所选国家/地区.
$scope.countries = [{name:'United States'},{name:'United Kingdom'},{name:'Canada'}];
$scope.filteredCountries = function(){
var filteredCountries = [];
angular.forEach($scope.countries,function(val,key){
if(val !== $scope.selectedCountry){
this.push(val);
}
},filteredCountries);
return filteredCountries;
};
您会注意到的错误是,只要您选择第二个,它就不会显示您选择的值,因为它会立即从选项中过滤掉.这不是最好的用户体验.
工作范例:
http://plnkr.co/edit/cRBdkE3akCeBXYqfyHFO
更新:
由于您不能在AngularUI Select2指令中使用ng-options,因此这是一个带有select 2示例的plunkr:http://plnkr.co/edit/Hmt1OXYvtHOAZPzW7YK3?p=preview
而不是上面列出的filteredCountries函数,手表将更有效.它只会在检测到监视值发生变化时运行代码.
$scope.$watch('version1model',function(){
$scope.filteredItems = [];
angular.forEach($scope.items,key){
if(val.id != $scope.version1model){
this.push(val);
}
},$scope.filteredItems);
});