如何过滤angularjs的值?

问题描述 投票:-1回答:2

我想过滤<select>的值。

我有一张第一列<select>的桌子。

例如:<select>的对象是JSON:

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

json2 = [{id: 1, name: 'ABC'}, {id: 2, name: 'DEF'}]

我的要求是:我们需要在ng-options中显示json1的值,但json2中不应该有哪个对象。

例如:前2行将用json2填充。所以我们需要在以下行中提供选项'XYZ''ASD'和'QWE'。

假设在第三行的下拉列表中选择了名称“XYZ”。然后第4排<select>应该只显示'ASD', and 'QWE'。类似地,在其他行中选择的对象不应该在其他行下拉选项中显示。

我尝试过这样的事情

 <select ng-model="obj"
         ng-options="obj.id as obj.name for obj in json1 | myFilter:json2">
</select>
myApp.filter('myFilter', function(json2) {
return function(json1) {
  var filtered = []; 

  json1.forEach((d) => {
   var exists = false;
      json2.forEach((ad) => {
         if(ad.id == d.id) {
           exists = true;
         }
      });
    if(!exists) filtered.push(d);
  });
  console.log(filetered); 
  return filtered.length > 0 ? filtered : json1;
};
});

在过滤器中,console.log()值按预期正确过滤。但是在ng-options中,json1的所有选项仍然无法使用过滤值更新。

怎么了?

angularjs angularjs-directive angularjs-ng-repeat angularjs-filter
2个回答
0
投票

这是你想要的?

例如:

<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'}];

App.filter('myfilter' , [function() {
    return function(json1, products, index) {
        // Filter all products, except the mime
        productsFilter = products.filter(function(product, i) {
                return i !== index;
        });

        // filter those that have not yet been selected
        var json1Filter = json1.filter(function(item) {

            // ask if there is the id in a product
            return !productsFilter.some(function(product) {
                return item.id == product.unique;
            });
        });
        return json1Filter;
    };
}]);

示例Codepen:https://codepen.io/anon/pen/vMJyLz


-1
投票

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

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

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

您的过滤器需要更新以检查是否应显示传递给过滤器的项目,如果不是,则返回false

你可以看看script example from the AngularJS docs,看看他们如何做到这一点,或其他Stack Overflow question/answer

© www.soinside.com 2019 - 2024. All rights reserved.