Can anyone explain what is happening in this code? I understand that link
function is executed after compile
.
link vs compile.js
is:
var app = angular.module('myApp', []);
app.directive('highlight', function () {
return {
restrict: 'A',
compile: function ($element, $attr, $transclude) {
console.log('executed highlight');
$element.addClass("highlight");
//$element.addClass("red");
}
};
});
app.directive('red', function () {
return {
restrict: 'A',
link: function ($scope, $element, $attr) {
console.log('executed red');
$element.addClass("red");
//$element.addClass("highlight");
}
};
});
link vs compile.html
is:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="js/angular.js" type="text/javascript"></script>
<script src="js/link vs compile.js" type="text/javascript"></script>
<style type="text/css">
.highlight{
background:yellow;
}
.red{
background: red;
}
</style>
</head>
<body>
<div ng-repeat="word in ['abc','def','ghi']" red highlight >
{{word}}
</div>
</body>
</html>
As a result of above is that div
appears with the red background color which makes sense as link
was executed later so it may have overwritten the effect compile
function. But when I change link vs compile.js
to this form:
var app = angular.module('myApp', []);
app.directive('highlight', function () {
return {
restrict: 'A',
compile: function ($element, $attr, $transclude) {
console.log('executed highlight');
//$element.addClass("highlight");
$element.addClass("red");
}
};
});
app.directive('red', function () {
return {
restrict: 'A',
link: function ($scope, $element, $attr) {
console.log('executed red');
//$element.addClass("red");
$element.addClass("highlight");
}
};
});
Now div
is with red
background, why is that? If link
function was executed later should not div
have yellow
color?