3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AngularJSで表とか作る時に、フィルタされた後の合計値とかも表示させたい時。

3
Last updated at Posted at 2015-05-11

ng-repeatで表とか作る時、カスタムフィルタとかでフィルタリングした後の合計値とかを使いたい。

Untitled.png

まあ、そんなに難しくなくて、

<tr ng-repeat="item in filteredItems=(main.items | filter:q)">

っていうのかキモかな。

index.html
<div ng-app="myApp">
  <div ng-controller="MainCtrl as main">
      <input ng-model="q"/>
    <table>
        <body>
            <tr ng-repeat="item in filteredItems=(main.items | filter:q)">
                <td>{{item.text}}</td>
                <td>{{item.amount}}</td>
            </tr>
            <tr>
                <td>sum</td>
                <td>{{filteredItems|sumFilter}}</td>
            </tr>
        </body>
    </table>
  </div>
</div>
"use strict";

angular.module("myApp", []);

//値を発生させる
angular.module("myApp").controller("MainCtrl", function(){
    this.items = [];
    for(var i = 0; i < 10; i++){
        this.items[i] = {
            text: "item" + i,
            amount: Math.round(1000 * Math.random())
        }
    }
});

//合計値計算フィルタ
angular.module("myApp").filter("sumFilter", function(){
    return function(input){
        var sum = 0;
        input.forEach(function(i){
            if(i.amount){
                sum = sum + i.amount;
            }
        });
        return sum;
    }
});

https://jsfiddle.net/wk3wjkjx/2/
こんな感じ。
業務用アプリとかでこういうことしている人はすでにいるでしょうかね。
もっといいやり方あったら教えて。

as

ng-repeatでasの記法を使うことができる。ということを@Quramyさんからコメントいただきました。
1.3.xから使えるのかなhttps://docs.angularjs.org/api/ng/directive/ngRepeat
https://jsfiddle.net/wk3wjkjx/3/
書き直して見ました。
こっちの方が見やすいですね。

3
4
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?