javascript - AngularJS:仅当它是另一个指令的子指令时才应用嵌入指令

标签 javascript angularjs parent directive

我想创建一个应用于 <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/

相关文章:

javascript - 在 VS Code 中调试时监 window 口或评估表达式?

javascript - 在 Angular 中注册事件的最佳方式

class - 在 extjs 3 上调用父类函数

angularjs - Angular UI Modal,避免模态范围更改反射(reflect)在父范围中

javascript - 使用 jQuery 删除父元素

java - 不明白这个JAVA类中从类内部调用父类

javascript - Lodash 如何使用双键将 _.grouby 一组数据加倍并 _.chain() 它们?

javascript - Vue 复制对象到本地数据

javascript - 使用 Javascript 下划线删除重复对象

javascript - AngularJS $resource 返回缓慢