繁体   English   中英

AngularJS过滤另一个数组中的值

[英]AngularJS Filter values which are in another array

我刚刚开始在AngularJS中使用过滤器。 我想要做的是使用一个简单的“选择框”将成分链接到产品。

在我的$ scope中,我有一个对象“ product”,其中除其他值外,还包含一个数组“ technicalProducts”。 这个数组包含所有与我当前产品相关的成分。 数组“ allCompositions”保存所有现有的组合。 不,每当链接了一个构图时,我都希望将其从Select-options中删除。 我认为最简单的方法是使用过滤器。

不幸的是,这行不通:

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

有什么建议吗?

过滤器在这里适合您的情况。 但是您必须定义一个自定义过滤器,因为默认过滤器仅适用于简单字符串。

// 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;
  });
})

然后以这种方式使用它:

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