gpt4 book ai didi

javascript - 如何控制在 AngularJS 中应用属性指令的顺序?

转载 作者:行者123 更新时间:2023-11-30 11:31:45 26 4
gpt4 key购买 nike

我有两个“A”指令。我想将它们应用于 div 元素。

我试图更改 html 文件中的顺序。我试图改变 JS 文件中的顺序。但结果是一样的——首先提醒 mydirective2,然后是 mydirective1。

如何改变顺序?我想要第一个 mydirective1,第二个 mydirective2。

ma​​in.js:

var app = angular.module("angularBlackbox", []);

app.directive("mydirective1", function () {
return {
restrict: "A",
link: function () {
alert("mydirective1 works!!!");
}
}
});

app.directive("mydirective2", function () {
return {
restrict: "A",
link: function () {
alert("mydirective2 works!!!");
}
}
});

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AngularJS Blackbox</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
</head>
<body>
<div ng-app="angularBlackbox">
<div mydirective1 mydirective2></div>
</div>

<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>

最佳答案

您可以在文档中使用 DDO 中的优先级

When there are multiple directives defined on a single DOM element, sometimes it is necessary to specify the order in which the directives are applied. The priority is used to sort the directives before their compile functions get called. Priority is defined as a number. Directives with greater numerical priority are compiled first. Pre-link functions are also run in priority order, but post-link functions are run in reverse order. The order of directives with the same priority is undefined. The default priority is 0

— AngularJS Comprehensive Directive API Reference - priority

var app = angular.module("angularBlackbox", []);

app.directive("mydirective1", function () {
return {
restrict: "A",
priority: 200,
link: function () {
alert("mydirective1 works!!!");
}
}
});

app.directive("mydirective2", function () {
return {
restrict: "A",
priority: 100,
link: function () {
alert("mydirective2 works!!!");
}
}
});

Understanding Priorities in AngularJS Directive Definition ObjectsDirective Priority in AngularJS博客很好地解释了 Angular Directive(指令)中的优先级

关于javascript - 如何控制在 AngularJS 中应用属性指令的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46001625/

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