简体   繁体   English

AngularJS过滤另一个数组中的值

[英]AngularJS Filter values which are in another array

I'm just getting started with using filters in AngularJS. 我刚刚开始在AngularJS中使用过滤器。 What I want to do is to link compositions to products, using a simple Select-box. 我想要做的是使用一个简单的“选择框”将成分链接到产品。

In my $scope, I have an object "product", which, among other values, contains an array "technicalProducts". 在我的$ scope中,我有一个对象“ product”,其中除其他值外,还包含一个数组“ technicalProducts”。 This array contains all compositions, which have been linked to my current product. 这个数组包含所有与我当前产品相关的成分。 The array "allCompositions" holds all existing compositions. 数组“ allCompositions”保存所有现有的组合。 No, whenever a composition has been linked, I want to remove it from the Select-options. 不,每当链接了一个构图时,我都希望将其从Select-options中删除。 I thought the easiest way to do this was by using a filter. 我认为最简单的方法是使用过滤器。

Unfortunately, this won't work: 不幸的是,这行不通:

<select class="form-control" name="compositions" id="compositions" ng-options="composition as composition.sysName for composition in allCompositions track by composition.sysName | filter:product.technicalProducts" ng-model="selComposition"></select>

Any advice? 有什么建议吗?

filter is good for your scenario here. 过滤器在这里适合您的情况。 But you have to define a custom filter because the default filter only works for simple string. 但是您必须定义一个自定义过滤器,因为默认过滤器仅适用于简单字符串。

// input for the target collection, args for the filter condition.
angularModule.filter('testFilter', function(input, args) {
  if (!args || args = '') return input;
  return input.filter(function(item) {
    return args.indexOf(item) === -1;
  });
})

then use it this way: 然后以这种方式使用它:

ng-options="composition as composition.sysName for composition in allCompositions | testFilter: product.technicalProducts track by composition.sysName"

 var app = angular.module("app", []); app.filter('testFilter', function() { return function(input, args) { if (!args || args === '') return input; return input.filter(function(item) { return args.indexOf(item) === -1; }); }; }); app.controller("myCtrl", function($scope) { $scope.selectedItem = 2; $scope.testArr = [ 1, 2, 3, 4, 5, 6, 7, 8 ]; $scope.testArr2 = [ 1, 3, 5, 7 ]; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.4/angular.min.js"></script> <div ng-app="app" ng-controller="myCtrl"> <select ng-options="item for item in testArr | testFilter: testArr2" ng-model="selectedItem"></select> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM