我想创建一个应用于 <tr>
的指令,但前提是它位于 <table parent-directive>
内,不是一个简单的<table>
。我不想为每个 <tr>
添加指令为了便于阅读,在我的表格中。
app.directive('tr', function() {
return {
transclude: 'element',
restrict: 'E',
require: '^parent-directive',
link: function ($scope, $element, $attr, ctrl, $transclude) {
//things to do only if child of <table parent-directive>
}
}
};
这里有一些问题:
- 如果我使用
<tr>
正常<table>
它会抛出一个错误。 - 如果我使用可选的 require
?^parent-directive
,我在其他<tr>
上有嵌入冲突指令ng-include
.
有没有办法有条件地应用指令?
最佳答案
据我所知,没有办法有条件地应用指令。
但是,还有另一种方法可以解决您的问题,一种逆转:使用 compile
parentDirective
的功能将子指令添加到所有 <tr>
它下面的元素,例如如:
app.directive('parentDirective', function() {
return {
restrict: 'A',
compile: function(tElem, tAttrs) {
tElem.find('tr').attr('child-directive', '');
}
};
});
查看概念证明 here 。请注意 child-directive
仅自动应用于 <table parent-directive>
的子级.
关于javascript - AngularJS:仅当它是另一个指令的子指令时才应用嵌入指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32519170/