2015-04-15 17 views
0

我有兩個字符串數組,title和title2,我想創建第三個匹配數組。我沒有用過濾器中的for循環運氣,但我想過使用forEach,但是,似乎需要字典類型對象。我正在嘗試創建一個篩選器,它將在兩個數組中找到匹配項

 .filter('findMatches', function() { 
     // this filter finds matching strings 
     return function isMatch(title, title2){ 
     var matches = []; 
     //for (i = 0; i < title.length; i++) { 
     matches.push(""); 

     return matches; 

我不知道這是有益的,但我以前寫這在Python,如下圖所示,不過,我想現在要做到這一點作爲一個angularJS過濾器,如果是動態查找matchies如果這是可能的。

Both = [] 
    for x in C: 
     if x in D: 
      Both.append(x) 
    for x in range(len(Both)): 
     Both[x]=str(Both[x]) 
    Final = [] 
    for x in set(Both): 
     Final.append(x) 
    MissingA = [] 
    for x in C: 
     if x not in Final and x not in MissingA: 
      MissingA.append(x) 
    for x in range(len(MissingA)): 
     MissingA[x]=str(MissingA[x]) 
    MissingB = [] 
    for x in D: 
     if x not in Final and x not in MissingB: 
      MissingB.append(x) 
    for x in range(len(MissingB)): 
     MissingB[x]=str(MissingB[x]) 

感謝您對下面兩個人的幫助。我仍然無法弄清楚。我在下面嘗試了方法二,但它不起作用。

http://plnkr.co/edit/SEi3DU0PoOSPx9AZBrzP?p=preview

回答

0

我不知道,一個自定義過濾器是一個不錯的選擇這個問題。我可能會創建一個將它作爲單個數組返回的服務,我可以執行匹配(或者只是讓服務執行匹配)。

一個簡單的解決辦法是像下面這樣雖然:

<input type="text" ng-model="query" /> 

    <ul> 
    <li ng-repeat="title in title1 | filter: query">{{title}}</li> 
    <li ng-repeat="title in title2 | filter: query">{{title}}</li> 
    </ul> 
0

,你可以簡單地做它作爲

.filter('findMatches', function() { 
     return function isMatch(title, title2){ 
      var matches = []; 
      for (i = 0; i < title.length; i++) { 
       if(title2.indexOf(title[i]) > -1){ 
       matches.push(title[i]); 
       } 
      } 
      return matches; 
     } 
}) 
相關問題