LoginSignup
8
8

More than 5 years have passed since last update.

要素内の変更をフックしたい

Last updated at Posted at 2014-08-09

JS、MutationObserverで、要素内の変更をフック出来て便利。

AngularJS、要素の大きさとか中身の変更を $watch できないと思うけど、これ使えば何とかなる。
試しにディレクティブ書いてみた。
http://jsfiddle.net/962e7dpv/

hook.gif

<hr>の下のdivを監視していて、変更があるとbodyの色がランダムに変わる。
フォームいじると監視してるdivに変更を加えられる。

ディレクティブの部分はこんな感じ。

angular.module('mgApp', [])
  .directive('mgHook', function () {
    return {
      link: function ($scope, $element, $attrs) {
        new MutationObserver(function () {
          $scope.$eval($attrs['mgHook']);
        }).observe($element[0], {
          attributes: true,
          characterData: true,
          childList: true,
          subtree: true
        });
      }
    };
  });

↑は他のdirectiveと併用する時独立したscope使うと怒られるから$evalとかやってる

別に併用しないなら↓でも良さそう

angular.module('mgApp', [])
  .directive('mgHook', function () {
    return {
      scope: {
        hook: '&mgHook'
      },
      link: function ($scope, $element, $attrs) {
        new MutationObserver(function () {
          $scope.hook();
        }).observe($element[0], {
          attributes: true,
          characterData: true,
          childList: true,
          subtree: true
        });
      }
    };
  });

注意

フックして呼ぶ関数内で監視してる要素を変更すると無限ループになる
observe()のパラメータ変更するなりして対処すると良さそう

8
8
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
8
8