<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@*" data-semver="1.3.4" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="demoModule">
<div>
<div id='left'>
<div class='wrapDirective' my-directive-compile></div>
</div>
<div id='right'>
<div class='wrapDirective' my-directive-link></div>
</div>
</div>
</body>
</html>
var myApp = angular.module('demoModule', []);
myApp.directive('myDirectiveCompile', function() {
return {
restrict: 'AE',
template: "<span>by Compile (click)</span>",
compile: function(element, attributes) {
element.css('background-color', 'green');
element.css('border', '1px solid black');
return {
pre: function() {
element.css('background-color', 'transparent');
},
post: element.on('click', function() {
changeBgColor(element);
})
}
}
};
});
myApp.directive('myDirectiveLink', function() {
return {
restrict: 'AE',
template: "<span>by Link (click)</span>",
link: {
pre: function preLink(scope, element, attributes) {
element.css('border', '1px solid black');
},
post: function postLink(scope, element, attributes) {
element.on('click', function() {
changeBgColor(element);
})
}
}
}
});
function changeBgColor(element) {
if (element.hasClass('changed')) {
element.css('background-color', 'transparent');
element.removeClass('changed');
} else {
element.css('background-color', 'yellow');
element.addClass('changed');
}
}
/* Styles go here */
#left{
float: left;
width: 50%;
}
#right{
float: right;
width: 50%;
}
.wrapDirective{
margin: 0px auto;
width: 90%;
text-align: center;
padding: 2px 0;
transition: all linear 1s;
}
Author: xuantain
Date: 29/11/2014
Description: Demo for compile function and link function.