angular compile/link process

Copied from http://plnkr.co/edit/qrDMJBlnwdNlfBqEEXL2

by loveky

HTML

<div ng-app="compilation">
    <div log-compile="parent">
        <div log-compile="..child 1">
            <div log-compile="....child 1 a"></div>
            <div log-compile="....child 1 b"></div>
        </div>
        <div log-compile="..child 2">
            <div log-compile="....child 2 a"></div>
            <div log-compile="....child 2 b"></div>
        </div>
    </div>
    <!-- LOG -->
<pre>{{log}}</pre>

</div>

CSS

div {
    padding: 5px;
    margin: 5px;
    background-color: #EEE;
    border: 1px solid #BBB;
}
div > div {
    background-color: #DDD;
}
div > div > div {
    background-color: #CCC;
}
ol {
    list-style: decimal;
    margin-left: 30px;
}

JavaScript

angular.module('compilation', [])

    .directive('logCompile', function ($rootScope) {
    $rootScope.log = "";

    return {
        controller: function ($scope, $attrs) {
            $rootScope.log = $rootScope.log + ($attrs.logCompile + ' (controller)\n');
        },
        compile: function compile(element, attributes) {
            $rootScope.log = $rootScope.log + (attributes.logCompile + ' (compile)\n');
            return {
                pre: function preLink(scope, element, attributes) {
                    $rootScope.log = $rootScope.log + (attributes.logCompile + ' (pre-link)\n');
                },
                post: function postLink(scope, element, attributes) {
                    element.prepend(attributes.logCompile);
                    $rootScope.log = $rootScope.log + (attributes.logCompile + ' (post-link)\n');
                }
            };
        }
    };
})

    .directive('terminate', function () {
    return {
        terminal: true
    };
});