如何使用 Angularjs 过滤器来过滤绑定到两个选择框的数组

How to use Angularjs filter to filter an array which has a binding to two select boxes

本文关键字:两个 选择 数组 过滤器 Angularjs 何使用 过滤 绑定      更新时间:2023-09-26

我有两个选择框(框 1 和框 2(绑定到模型数组。在框 1 中选择一个选项时,该项目不应显示在框 2 中,反之亦然。我怎样才能在Angularjs中做到这一点。

下面是我的网页

<select class="form-control" name"box1" ng-model="data.box1" ng-options="sq.text for sq in array1.boxvalue | filter :data.box1" required><option value="">Choose 1</option></select>
<select class="form-control" name"box2" ng-model="data.box2" ng-options="sq.text for sq in array1.boxvalue | filter: data.box1"" required><option value="">Choose 2</option></select>
array1.boxvalue = {['id':1,'text':'test1'],['id':2,'text':'test2'],['id':3,'text':'test3']}

如何实现以下目标:在 box1 中选择 test1 时,box2 下拉列表不应显示 test1,反之亦然。

谢谢

你的想法是正确的,你需要一个过滤器来通过数组并排除你不喜欢的值。

(我正在编写代码,所以我不确定它是否 100% 有效。

app.filter('excludeValue', function() {
    return function(input, val) {
        var newArray = [];
        //Loop through all the results and remove the one that is not needed
        for( var n = 0 ; n < input.length; n++) { 
            //Check if current value is not the same as a value we need to exclude
            if(input[n] != val) { 
                newArray.push(input[n]);
            }
        } 
        return newArray;
    };
});

编辑:这是一个工作弹道

视图:

   <select    ng-model="data.box1" 
  ng-options="sq.text for sq in array1 | filter: notinbox2" required></select>
<select    ng-model="data.box2" ng-options="sq.text for sq in array1 |filter: notinbox1" required></select>

控制器:

$scope.array1 =[{'id':1,'text':'test1'},{'id':2,'text':'test2'},{'id':3,'text':'test3'}]
        $scope.data={}
        $scope.notinbox2 = function(item){
            if(item == $scope.data.box2)
                {
                return false
                }
            else 
                return true
        }
        $scope.notinbox1 = function(item){
            if(item == $scope.data.box1)
                {
                return false
                }
            else 
                return true
        }

从你的问题中简单地说了几件事

普伦克 [http://plnkr.co/edit/NM7ovJ3wIpLohYIiDsu2?p=info]