如何在angularjs中过滤<select>的值?

时间:2019-04-12 17:54:42

标签: angularjs angularjs-directive angularjs-ng-repeat angularjs-filter

我想过滤的表。 例如:应该仅显示“ ASD”和“ QWE”。同样,在其他行下拉菜单中不应显示在其他行中选择的对象。 我已经尝试过这样的事情   myApp.filter('myFilter',function(json2){ 返回函数(json1){   var filtered = [];   json1.forEach((d)=> {    var exist = false;       json2.forEach((ad)=> {          if(ad.id == d.id){            存在=真;          }       });     if(!exists)filtered.push(d);   });   console.log(过滤);   返回filtered.length> 0?过滤:json1; }; }); 在过滤器中,console.log()值已按预期正确过滤。但是,在ng-options中,json1中的所有选项仍然可用,但不会使用过滤后的值进行更新。 怎么了?

2 个答案:

答案 0 :(得分:0)

这是您要寻找的吗?

例如:

  Confirmed uniq_0(data) == golden
  Confirmed uniq_1(data) == golden
  Confirmed uniq_2(data) == golden
  Confirmed uniq_3(data) == golden
  Confirmed uniq_4(data) == golden
  Confirmed uniq_5(data) == golden
  Confirmed uniq_6(data) == golden

In [73]: # 1000 Series. Averaging 10000.0 ints/Series. 405 ints unique.

In [74]: for f in funcs:
    ...:     print(f.__name__, end=': ')
    ...:     %timeit -r 3 f(data2)
uniq_0: 2.21 s ± 18.5 ms per loop (mean ± std. dev. of 3 runs, 1 loop each)
uniq_1: 465 ms ± 2.5 ms per loop (mean ± std. dev. of 3 runs, 1 loop each)
uniq_2: 126 ms ± 215 µs per loop (mean ± std. dev. of 3 runs, 10 loops each)
uniq_3: 2.22 s ± 48.6 ms per loop (mean ± std. dev. of 3 runs, 1 loop each)
uniq_4: 1.12 s ± 10.8 ms per loop (mean ± std. dev. of 3 runs, 1 loop each)
uniq_5: 374 ms ± 1.28 ms per loop (mean ± std. dev. of 3 runs, 1 loop each)
uniq_6: 831 ms ± 20.6 ms per loop (mean ± std. dev. of 3 runs, 1 loop each)

In [75]: 

<table>
<thead>
    <tr>
        <th>Unique</th>
        <th>Name</th>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="product in products">
        <td>
            <select ng-model="product.unique" ng-options="obj.id as obj.name for obj in (json1 | myfilter:products:$index)">
                <option value="">No select</option>
            </select>
        </td>
        <td ng-bind="product.name"></td>
    </tr>
</tbody>
</table>

vm.products = [{name: 'Product 1'}, {name: 'Product 2'}, {name: 'Product 3'}, {name: 'Product 4'}, {name: 'Product 5'}];
vm.json1 = [{id: 1, name: 'ABC'}, {id: 2, name: 'DEF'}, {id: 3, name: 'XYZ'}, {id: 4, name: 'ASD'}, {id: 5, name: 'QWE'}];

示例代码笔:https://codepen.io/anon/pen/vMJyLz

答案 1 :(得分:-1)

我认为您的过滤器参数有些错误。过滤器函数将第一个参数作为要过滤的值,其他参数是myFilter:之后的参数。

我不确定您要在这里发生什么,但是您为下拉列表中的每个值都会调用您的过滤器函数,并且应该返回给定值的替换值。

但是,您的代码返回的是一组项目。这不是AngularJS中过滤器的工作方式。

您的过滤器需要更新,以检查是否应该显示传递到过滤器中的项目,否则,请返回false

您可以查看script example from the AngularJS docs来看看他们显示如何执行此操作,或者查看其他Stack Overflow question/answer的显示方式。