Thursday 1 October 2015

directive link prelink & compile & controller

var app = angular.module('app', []);
app.directive('dad', function () {
    return {
        restrict: 'EA',
        template: '<div class="dad">{{greeting}}{{name}}'+
        '<son></son>'+
        '</div>',
        link: {
            pre: function(scope,elem,attr) {
                scope.name = 'Paul';
                scope.greeting = 'Hey, I am ';
            }
        }
    };
});
app.directive('son', function () {
    return {
        restrict: 'EA',
        template: '<div class="son">{{sonSays}}</div>',
        link: function(scope,elem,attr){
            alert("son");
            scope.sonSays = 'Hey, I am son, and my dad is '+ scope.name;
        }
    };
});

      app.directive('compileExample', compileExample);

    function compileExample() {
      return {
        restrict: 'E',
        scope:{
            type:"="
        },
          bindToController:true,
   controllerAs:'vm',
   controller:function($scope) {
       alert("controller");
   },
        compile: function(tElement, tAttrs) {
            if (tAttrs.type === "new") {
                 angular.element(tElement).append("My new name is {{name}}");
            } else {
                angular.element(tElement).append("My name is {{name}}");
            }
          alert("compile"+tAttrs.type);
          return function postLink(scope, element, attrs) {
              alert("compile postLink");
            scope.name = 'David'
          }
        }
      }
    }