JSFiddle - React, Tailwind, and code Playground
by dameleon
HTML
<div ng-app="sample">
<p>consoleで確認のこと</p>
<dl>
<dt>呼び出しタイミングの違い</dt>
<dd>
<hoge ng-repeat="i in [0,1,2]"></hoge>
</dd>
<dt>transcludeの挙動</dt>
<dd>
<hoge-transclude><piyo></piyo></hoge-transclude>
<fuga-transclude><piyo></piyo></fuga-transclude>
</dd>
</dl>
</div>
JavaScript
var module = angular.module('sample', []);
////////////////// 呼び出しタイミングの違い
module.directive('hoge', function() {
return {
restrict: 'E',
template: '<div>hoge{{ i }}</div>',
compile: function(element, attrs, transclude) {
// compile は HTML 上の1ディレクティブで1回しか走らないので、ここは1度しか呼ばれない
console.log('hoge compile', arguments);
// 返す link 用の関数は link のタイミングで行われるため、上記のような HTML の場合、3回呼ばれる
var preCount = postCount = 0;
return {
pre: function() { console.log('hoge preLink count: ' + (++preCount), arguments); },
post: function() { console.log('hoge postLink count: ' + (++postCount), arguments); }
};
}
};
});
////////////////// transcludeの挙動
module.directive('hogeTransclude', function() {
return {
restrict: 'E',
transclude: true,
template: '<div ng-transclude></div>',
compile: function(element, attr, tranclude) {
// compile と link で tranclude の実体が違う
console.log('hoge-transclude', tranclude, tranclude({}, function() {
console.log(arguments);
}));
}
};
});
module.directive('fugaTransclude', function() {
return {
restrict: 'E',
transclude: true,
template: '<div ng-transclude></div>',
link: function(scope, element, attr, controller, tranclude) {
// compile と link で tranclude の実体が違う
console.log('fuga-transclude', tranclude, tranclude(scope, function() {
console.log(arguments);
}));
}
};
});
module.directive('piyo', function() {
return {
restrict: 'E',
template: 'ぴよぴよ',
}
});