2017-03-23 11 views
0

AngularJSでフィルタを使用し始めたばかりです。私がしたいのは、シンプルなSelectボックスを使ってコンポジションをプロダクトにリンクすることです。AngularJS別の配列にあるフィルタ値

my $ scopeには、オブジェクト "product"があります。他の値の中には配列 "technicalProducts"が含まれています。この配列には、現在の製品にリンクされているすべてのコンポジションが含まれています。配列 "allCompositions"は、すべての既存のの構成を保持します。 いいえ、コンポジションがリンクされている場合は、それを[選択]オプションから削除します。私はこれを行う最も簡単な方法は、フィルタを使用することだと思った。

残念ながら、これは動作しません。

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

任意のアドバイスはありますか?

答えて

1

ここではフィルタが適しています。しかし、デフォルトフィルタは単純な文字列に対してのみ機能するため、カスタムフィルタを定義する必要があります。

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

+0

は、あなたの入力をありがとう!残念ながら、このカスタムフィルタを使用しようとすると、値がビューから正しく渡されないかのように、「入力」は常に定義されません。 – DCH

+0

@DCH私は自分の答えを更新しました。表現の最後に "track by"ステートメントを移動する必要があるという表現には別の誤りがあります。 – Pengyy

+0

説明した問題は、私の作品の非同期読み込みによるものです。しかし、私は何を返さなければならないのか分かりません。 falseまたはtrueを返すだけで、要素が選択リストにオプションとして追加されます。空のStringまたはnullを返すと、すでにリンクされている場合でも要素が追加されます。 – DCH

関連する問題