2015-04-12 88 views
1

我正在創建一個網站,其中我有對象,都具有'標記'屬性,這是一個字符串列表。過濾只有一個屬性或所有字段

我正在創建一個搜索功能來過濾列表中的所有元素。如果用戶輸入'#something here',那麼我只想將用戶輸入與每個屬性的標籤匹配。如果用戶只是在搜索框中輸入一個字符串,那麼我想搜索所有的對象屬性。

我有一個像這樣定義的一種形式:

<form class="navbar-form navbar-left" role="search"> 
    <div class="form-group"> 
    <input data-ng-model="$root.searchText" type="text" class="form-control" placeholder="#hashtag or just a string"> 
    </div> 
</form> 

我知道,默認的過濾器可以在我希望的方式來,如果我定義數據-NG-模型,我想現場。所以如果我只想搜索標籤,我會做data-ng-model ='$ root.searchText.tags',用戶輸入只會匹配。如果我想搜索所有,那麼我會做data-ng-model ='$ root.searchText。$'。

但是,如何根據用戶是否在開頭輸入帶'#'的字符串來開啓模型切換?

我試過創建一個自定義的過濾器,但這讓人困惑。應該有某種條件語句將模型設置爲$ root.searchText.tags或$ root.searchText。$,但這更難以實現。有誰知道如何構造該條件語句?

回答

1

我有一個解決方案給你,雖然它可能不是最好的解決方法。 你看的搜索過濾器和更新列表根據您的邏輯:

1.filter的標籤,如果SEARCHTEXT通過屬性的值以「#」開始

2.fitler如果SEARCHTEXT做開始與' #」

$scope.$watch('model.search', function(search){ 
    var tagFilter,results; 
     if(search.startsWith('#')) { //handle tag filter logic 
     tagFilters = search.split('#'); 
     console.log(tagFilters); 
     results = _.filter($scope.model.lists, function(obj){ 
      return _.intersection(obj.tags, tagFilters).length > 0; 
     }); 
     } else { //handle property filter logic 
     results = _.filter($scope.model.lists, function (obj) { 
      return _.values(obj).some(function (el) { 
       return el.indexOf(search) > -1; 
      }); 
     }); 
     } 
     console.log(results); 
     $scope.model.displayItems = results; 

    }, true); 

plnkr

+0

這很適合!現在唯一的問題是,在頁面加載時,我自己代碼中的$ scope.model.lists實際上是空的,必須從數據庫異步查詢。所以當頁面第一次加載時屏幕上沒有任何內容,因爲手錶過濾器運行時有一個空的列表。 – Maharlikans