任何人都可以解釋這段代碼中發生了什麼嗎?我明白link
函數是在compile
之後執行的。在AngularJS的編譯功能中使用鏈接函數中的addClass與uisng addClass
link vs compile.js
是:
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
是:
<!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>
作爲以上的結果是,div
顯示與紅色的背景色爲link
後來執行,從而它可以具有其中有意義覆蓋效果compile
功能。但是,當我改變link vs compile.js
這種形式:
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");
}
};
});
現在div
是red
的背景下,這是爲什麼?如果link
功能被執行後不應該div
有yellow
顏色?
代碼@http://plnkr.co/edit/RJtnuVHtZvgFAraG2eVa?p=preview
要了解編譯和鏈接的區別:HTTP://stackoverflow.com/questions/12164138/what-is-the-difference-between-compile-and-link-function -in-angularjs – Reza
@Reza該鏈接沒有解決這個特定的問題。 – user4904589
也許你的div有兩個類,所以你會得到意想不到的結果,嘗試添加高級類時刪除紅色類,反之亦然 –