14
14

More than 5 years have passed since last update.

AngularJSのfilterでよく使用するパターン

Last updated at Posted at 2014-01-02

部分一致

いずれかの列に、部分一致する行を抽出する。

コントローラ定義

一覧表示するオブジェクトを定義する。

function TodoCtr($scope){
    $scope.items = [
                    {taskName:"AAA",priority:"Low"},
                    {taskName:"BBB",priority:"High"},
                    {taskName:"CCC",priority:"Middle"}
                  ];}

HTML

検索キーワードを入力するinputのng-modelと、filterへ渡すプロパティ名を一致させる。

<body ng-controller="TodoCtr">
    <label>Search BOX</label> 
    <input type="text" style="width:200px;" ng-model="searchText">
    <table>
            <thead>
                <tr><th>Task</th>
                    <th>Priority</th>
                </tr>
            </thead>
            <tbody ng-repeat="item in items | filter:searchText">
                <tr>
                    <td>{{item.taskName}}</td>
                    <td>{{item.priority}}</td>
                </tr>
            </tbody>
    </table>
</body>

実行結果

「Task」「Priority」のいずれかに、部分一致する行が抽出される。

部分一致 (特定項目のみ対象とする)

特定の列に、部分一致する行を抽出する。

HTML

検索キーワードのng-modelに[.検索対象プロパティ名]を付与する。

<input type="text" style="width:200px;" ng-model="searchText.taskName”>

実行結果

「Task」に部分一致する行が抽出される。

完全一致

いずれかの列に、完全一致する行を抽出する。

HTML

filterの2つ目の引数にtrueを渡す。(デフォルトはfalse)

<tbody ng-repeat="item in items | filter:searchText:true">

実行結果

「Task」「Priority」のいずれかに、完全一致する行が抽出される。

部分一致 (大文字小文字を区別する)

いずれかの列に、「大文字小文字を区別して」部分一致する行を抽出する。

コントローラ定義

デフォルトで用意されているオプションではできないはずなので、比較ルールをコントローラに実装する。

function TodoCtr($scope){

    $scope.caseSensitive = function(expected, actual){
      // expectedに各項目の値が渡され、actualに入力した検索ワードが渡される。
      // 大文字小文字を揃えずに判定する
      return expected.indexOf(actual) > -1;
    }

    //省略

HTML

filterの2つ目の引数に定義した関数名を渡す。

<tbody ng-repeat="item in items | filter:searchText:caseSensitive">

実行結果

「Task」「Priority」のいずれかに、「大文字小文字を区別して」部分一致する行が抽出される。

14
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
14