LoginSignup
21
22

More than 5 years have passed since last update.

Angularjsのng-repeatを描画完了してから処理したい時

Last updated at Posted at 2015-08-19

angularjsの超初心者向けの内容になってますので上級者は戻るボタン推奨です(^q^)

ng-repeatでループを終了させたタイミングで処理をしたい時ってありますよね。
そんな時に役立つディレクティブを紹介します。

angular.module("myApp", [])
  .directive("repeatFinished", function(){
    return function(scope, element, attrs){
      if (scope.$last){
        //ループが最後である時呼ばれます
        scope.$emit("repeatFinishedEventFired"); //ファイヤー!!
      }
    }
  });

あとは着火したイベントを見張る

$scope.$on('repeatFinishedEventFired', function() {
  //何かする。転職するとか...
}

しかし、これは確かにループ終了後なのですが描画が完了したタイミングではありません。
jQueryなどの外部ライブラリとの連携をするにはDOMが描画完了したタイミングで処理したいですよね。

そこで

angular.module("myApp", [])
  .directive("repeatFinished", function($timeout){
    return function(scope, element, attrs){
      if (scope.$last){
        //魔法の言葉を付け加える
        $timeout(function(){
          scope.$emit("repeatFinishedEventFired"); //イベント着火!
        });
      }
    }
  });

魔法の言葉 $timeout って何ですんの?
って話ですが、$timeoutにはsetTimeoutscope.$applyがセットになっております。

別のエントリでも書きましたが、TypeSciptだと一工夫必要なの一応載せておきますね

class repeatFinished implements ng.IDirective
{
  static timeoutService : ng.ITimeoutService;

  public constructor($timeout : ng.ITimeoutService){
    repeatFinished.timeoutService = $timeout;
  }

  public link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs : ng.IAttributes){
    if (scope.$last){
      repeatFinished.timeoutService(() => {
        scope.$emit("repeatFinishedEventFired");
      });
    }
  }
}
//前回はfactoryにしましたが、今回は呼び出し元でクロージャ
angular.module("myApp", []).directive("repeatFinished", ($timeout: ng.ITimeoutService) => {
    return new MyDirective($timeout);
});

Angularjsって何だよ。って人には良い事しか書いてないブログもあるのでどうぞ
Angularjs超入門。最高のJavaScriptフレームワークを紹介します

21
22
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
21
22