2014-11-14 25 views
5

我的應用程序的幾個部分中的一個非常常見的功能是接受字符串然後根據字符串過濾表的搜索框。在angularJs中編程搜索文本框的正確方法

我的目標是允許用戶鍵入某些內容,並在幾ms延遲後自動更新結果。即不需要點擊輸入按鈕。

數據的當然排序將使用AngularJs過濾器完成。然而,在我們更新過濾器之前,我相信我們首先必須瞭解用戶已經完成輸入並正在等待結果。

因此,我制定了將附加到搜索輸入框的指令。

<input type="text" update-filter placeholder="Enter search term"> 


//and the directive goes like this 
app.directive('updateFilter', [ '$timeout', function($timeout){ 
    var delay; 
    return { 
    link: function(scope, element){ 
     element.on('keypress', function(){ 
      if(!delay) { 
       delay = $timeout(function() { 
        //perform the activity of updating the filter here 
       delay = undefined; 
       },50); 
      } 
     } 
    } 
    } 
}); 

我的問題是,這是正確的做法採取解決這個問題還是有更好的解決方案了嗎?

回答

9

你太過於複雜了。它可以在角度上更容易完成。

<input type="text" ng-model="query" ng-model-options="{ debounce: 200 }" 
    ng-change="doSearch()"> 

使用$scope.query訪問控制器中的查詢。定義$scope.doSearch()進行搜索。反彈選項用於在用戶輸入完畢後等待200毫秒。

5

當我編寫過濾器時,我在過濾器輸入上使用了ng-model來訪問過濾器值,然後直接在ng-repeat過濾器值中使用該值。舉例來說,這裏的投入,得到過濾器值:

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

,這裏是一個重複錶行,由值過濾上述建模:

<tr ng-repeat="user in users | filter: user_filter"> 

只要你鍵入,角註冊新值並應用過濾器。無需等待或執行任何操作,因爲角度會爲您應用映射的值。

查看Angular docs on filter。它在頁面底部有一個工作示例,展示了這個實際操作。

+0

這隻有在客戶端擁有所有數據時纔有效。 – CodesInChaos 2015-06-16 13:53:39

+0

@CodesInChaos - true,它只會過濾加載到應用程序中的數據。 – 2015-06-16 20:55:11