ng-directiveのscope

2014-07-20T00:00:00+00:00 angular.js JavaScript

参考: AngularJSのdirectiveとは

<html ng-app="sample"
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.14/angular.min.js"></script>
    <script src="main.js"></script>
  </head>
  <body>
    <div ng-controller="SampleCtrl">
      <h4>controller: {% raw %}{{message}}{% endraw %}</h4>
      <div directive1>
        <h4>directive1: {% raw %}{{message}}{% endraw %}</h4>
        <div directive2>
          <h4>directive2: {% raw %}{{message}}{% endraw %}</h4>
        </div>
      </div>
    </div>
  </body>
</html>

っていうのに作ったng-directiveに対してscopeを設定するかしないかで何が変わるのか検証してみた

directive1だけをscope:trueにした場合

angular.module("sample", [])
  .controller("SampleCtrl", function($scope) {
    $scope.message = "hoge"
  })
  .directive("directive1", function() {
    return {
      scope: true,
      link: function(scope, element, attrs) {
        scope.message = "fuga";
      }
    };
  })
  .directive("directive2", function() {
    return {
      link: function(scope, element, attrs) {
        scope.message = "A";
      }
    };
  });

結果は

directive1にネストされているdirective2でのscopeの反映がレンダリングまでは伝搬されてない? というよりはあくまで参照されるスコープコンテキストがdirective1になる的な感じだろうか

directive2もscope:trueにした場合

angular.module("sample", [])
  .controller("SampleCtrl", function($scope) {
    $scope.message = "hoge"
  })
  .directive("directive1", function() {
    return {
      scope: true,
      link: function(scope, element, attrs) {
        scope.message = "fuga";
      }
    };
  })
  .directive("directive2", function() {
    return {
      scope: true,
      link: function(scope, element, attrs) {
        scope.message = "A";
      }
    };
  });

結果は

っていうような感じでdirective2ではdirective2なスコープコンテキストが作用する。上記でdirective1だけscope:trueにした場合と結果が違うのはdirective2で指定されているエレメント等において参照されるコンテキストなスコープがdirective1のスコープを親として新しいスコープを生成する。directive1.scope == directive2.scopeでは無いっていう事かと

そういう事象もあるって事でメモ

余談

ちなみにng-directiveでとあるdirectiveに依存にするようなdirectiveを作る場合にはちゃんとrequireで^を使って親のdirectiveによる依存を設定するべきかと

それともう一件

Railsのconcernsについて rails g migration