如果我在另一个指令的模板中包含一个指令并将transclude
内容包含在其中,那么它的链接函数会在任何一个被转换的指令之前被调用。
例如(也在JSFiddle上):
我有以下由指令和模板组成的HTML。
<body ng-app="showcase">
<reel>
<asset></asset>
</reel>
<script type="text/ng-template" id="reel.html">
<div class="reel">
<div class="inner" scrollable ng-transclude></div>
</div>
</script>
<script type="text/ng-template" id="asset.html">
<div class="asset" ng-transclude></div>
</script>
</body>
并设置我的指令。
var app = angular.module('showcase', []);
app.directive('reel', function() {
return {
restrict: 'E',
replace: true,
transclude: true,
templateUrl:'reel.html',
link: function() { console.log('reel'); }
};
});
app.directive('scrollable', function() {
return {
terminal: true,
restrict: 'A',
link: function() { console.log("scrollable"); }
};
});
app.directive('asset', function() {
return {
restrict: 'E',
replace: true,
transclude: true,
templateUrl: 'asset.html',
link: function() { console.log('asset'); }
};
});
进入控制台的预期输出为:
asset
scrollable
reel
因为asset
是scrollable
的孩子,所以我得到:
scrollable
asset
reel
有谁知道如何才能获得我的订单,但仍然在reel
模板中定义附加指令?
答案 0 :(得分:1)
如果您在同一元素上使用指令,则需要设置优先级。默认情况下,用户定义的指令优先级为0.尝试将资产设置为优先级:10。
/** ### Directive Definition Object
*
* The directive definition object provides instructions to the {@link ng.$compile
* compiler}. The attributes are:
*
* #### `priority`
* 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`.
*
* #### `terminal`
* If set to true then the current `priority` will be the last set of directives
* which will execute (any directives at the current priority will still execute
* as the order of execution on same `priority` is undefined).
*/