【发布时间】:2015-10-18 14:44:11
【问题描述】:
谁能解释这段代码发生了什么?我知道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");
}
};
});
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颜色吗?
【问题讨论】:
-
了解编译和链接的区别:stackoverflow.com/questions/12164138/…
-
@Reza 该链接没有解决这个特定问题。
-
可能你的 div 有两个类所以你会得到意想不到的结果,添加高亮类时尝试删除红色类,反之亦然
标签: javascript html css angularjs