【问题标题】:How to use Angularjs filter to filter an array which has a binding to two select boxes如何使用Angularjs过滤器过滤绑定到两个选择框的数组
【发布时间】:2014-12-18 10:14:18
【问题描述】:

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

下面是我的 HTML

<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,反之亦然。

谢谢

【问题讨论】:

    标签: javascript jquery angularjs angularjs-filter


    【解决方案1】:

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

    (我正在编写代码,所以我不确定它是否 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;
        };
    });
    

    编辑:这是一个有效的plunker

    【讨论】:

      【解决方案2】:

      查看:

         <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
      
              }
      

      从你的问题中简化了几件事

      Plunker [http://plnkr.co/edit/NM7ovJ3wIpLohYIiDsu2?p=info]

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-17
        • 2017-01-24
        • 1970-01-01
        • 2014-07-21
        • 1970-01-01
        • 2016-09-08
        相关资源
        最近更新 更多