gpt4 book ai didi

javascript - 在 Link 函数中使用 add Class 与在 AngularJS 的 Compile 函数中使用 addClass

转载 作者:太空宇宙 更新时间:2023-11-04 11:16:11 25 4
gpt4 key购买 nike

谁能解释这段代码中发生了什么?我明白 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");

}
};
});

现在 divred 背景,这是为什么?如果稍后执行 link 函数,div 不应该有 yellow 颜色吗?

代码@ http://plnkr.co/edit/RJtnuVHtZvgFAraG2eVa?p=preview

最佳答案

这不是关于 angularjs 的 链接编译,这是关于 css

<div class="highlight red">my div</div> 

如果你改变类的顺序什么都不会发生

<div class="red highlight">my div</div>

更多详情:How to specifiy the order of CSS classes?

关于javascript - 在 Link 函数中使用 add Class 与在 AngularJS 的 Compile 函数中使用 addClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33194843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com