Angularjsのfilterをcontrollerから使う

ハマっていたので覚書としてメモ。

Angularjsのfilterは便利です。配列やら文字列やらオブジェクトやらを渡して、もにょもにょ処理できますし、Viewにバインドするだけで簡単に使えます。超便利。

Demo on Plunker

当然こんなに便利だとControllerの中でも使いたくなりますね。
僕はなりました。で、Serviceなどと同じようにDIで呼び出す場合にはこんなかんじに書くのですが、

angular.module('appName').filter('customFilter', function () { ... filter logic ...});

この状態で以下のようにControllerからDIしようとするとInjectionを解決できずにエラーになります。

sampleCtrl = function ($scope, customeFilter) {}; // <- customeFilterのinjectionでエラー

しばらくハマっていたのですが、API docではなくてGuideの方にきちんと書いてありました。

You can also use filters in controllers and services. For this, add a dependency with the
 name <filterName>Filter to your controller or service. E.g. using the dependency
 numberFilter will inject the number filter. The injected argument is a function that takes
 the value to format as first argument and filter parameters starting with the second
 argument.

簡単に言うと filterName + Filter という名前でinjectされるよ!ということです。 それにしたがって書きなおしてみると。。。

angular.module('appName').filter('custom', function () { ... filter logic ...});
sampleCtrl = function ($scope, customeFilter) {};

こんなかんじになります。
これでControllerの中でも便利なFilterを再利用することができるようになりました。
やりましたね:)

JavaScript ライブラリ実践活用〔厳選111〕 (Software Design plus)

JavaScript ライブラリ実践活用〔厳選111〕 (Software Design plus)

AngularJS

AngularJS