Angularjsのfilterをcontrollerから使う
ハマっていたので覚書としてメモ。
Angularjsのfilterは便利です。配列やら文字列やらオブジェクトやらを渡して、もにょもにょ処理できますし、Viewにバインドするだけで簡単に使えます。超便利。
当然こんなに便利だと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)
- 作者: WINGSプロジェクト,山田祥寛,安西剛,高江賢,高野将
- 出版社/メーカー: 技術評論社
- 発売日: 2013/03/20
- メディア: 大型本
- クリック: 12回
- この商品を含むブログ (8件) を見る
- 作者: Brad Green,Shyam Seshadri
- 出版社/メーカー: O'Reilly Media
- 発売日: 2013/04/08
- メディア: Kindle版
- この商品を含むブログを見る