【发布时间】:2023-03-22 01:15:02
【问题描述】:
我在 angular.js 模块中定义了两个指令。声明的 HTML 元素首先执行它的指令,但使用另一个指令的第二个 HTML 元素不执行它。
鉴于此 HTML:
<div ng-app="myApp">
<div ng-controller="PlayersCtrl">
<div primary text="{{primaryText}}"/>
<div secondary text="{{secondaryText}}"/>
</div>
</div>
还有这个 angular.js 代码:
var myApp = angular.module('myApp', []);
function PlayersCtrl($scope) {
$scope.primaryText = "Players";
$scope.secondaryText = "the best player list";
}
myApp.directive('primary', function(){
return {
scope: {
text: '@'
},
template: '<h1>{{text}}</h1>',
link: function(scope, element, attrs){
console.log('primary directive');
}
};
});
myApp.directive('secondary', function(){
return {
scope: {
text: '@'
},
template: '<h3>{{text}}</h3>',
link: function(scope, element, attrs){
console.log('secondary directive');
}
};
});
生成的 HTML 只是“主要”指令,“次要”指令不呈现:
<div ng-app="myApp" class="ng-scope">
<div ng-controller="PlayersCtrl" class="ng-scope">
<div primary="" text="Players" class="ng-isolate-scope ng-scope">
<h1 class="ng-binding">Players</h1>
</div>
</div>
</div>
控制台输出也验证了这一点,因为仅输出“主指令”文本。
那么如果我切换主次元素的顺序,secondary指令执行,primary指令不执行:
<!-- reversed elements -->
<div secondary text="{{secondaryText}}"/>
<div primary text="{{primaryText}}"/>
<!-- renders this HTML (secondary, no primary) -->
<div ng-app="myApp" class="ng-scope">
<div ng-controller="PlayersCtrl" class="ng-scope">
<div secondary="" text="the best player list" class="ng-isolate-scope ng-scope">
<h3 class="ng-binding">the best player list</h3>
</div>
</div>
</div>
这是为什么?我做错了什么?
【问题讨论】:
-
答案是嵌入。
-
Transclusion跟这个无关,是简单的HTML语法错误。
-
在阅读了嵌入并在我的指令中使用它之后,它起作用并解决了问题。我不知道为什么。这在当时似乎也没有意义。无论如何,我还是开枪了。
-
Transclusion 似乎可以解决问题,因为它可能已将
secondary元素附加到primary元素而不是兄弟姐妹。
标签: javascript html angularjs angularjs-directive