检测 AngularJS 指令中是否使用了可选的嵌入元素?

sha*_*lla 5 angularjs angularjs-directive angularjs-ng-transclude

我有一个如下所示样式的指令;它允许可选的嵌入元素,例如示例中使用的<dir-header>和。<dir-footer>

\n\n

指令.js(部分)

\n\n
module.directive(\'dir\', function () {\n    return {\n        restrict: \'E\',\n        templateUrl: \'path/template.html\',\n        transclude: {\n            \'header\': \'?dirHeader\',\n            \'footer\': \'?dirFooter\'\n        },\n        link: function (scope, elem, attrs) {\n            // do something\n        }\n    };\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

模板.html

\n\n
<div ng-transclude="header">\n  <!-- Transcluded header will appear here -->\n</div>\n\n<div class="static-content">\n    Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n</div>\n\n<div ng-transclude="footer">\n    <!-- Transcluded footer will appear here -->\n</div>\n
Run Code Online (Sandbox Code Playgroud)\n\n

用法

\n\n
<dir>\n    <dir-header>My Header</dir-header>\n    <dir-footer>My Footer</dir-footer>\n</dir>\n
Run Code Online (Sandbox Code Playgroud)\n\n

根据我这里的内容,有没有办法检测是否<dir-header>正在使用?"My header"我可以从链接函数访问传递到其中的内容\xe2\x80\x94(在本例中为字符串\xe2\x80\x94)吗?

\n\n
\n\n

到目前为止我所做的一些背景:

\n\n

我已经看到一些使用 样式transclude: true而不是transclude: {}. 根据该研究的建议,我尝试了以下方法:

\n\n
link: function (scope, elem, attrs, $transclude) {\n    $transclude(function (clone) {\n        console.log(clone);\n    });\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我不太清楚克隆是如何工作的,但它似乎是一个代表已被嵌入的内容的 NodeList。不幸的是,我从中得到的唯一有用的信息是长度;clone.length对于我上面的用法示例,为 3(其中一个代表dirheaderfooter)。如果我删除footer长度将为 2,依此类推。不过,似乎没有任何数据可以区分 NodeList 中的元素,因此我无法判断正在使用哪些嵌入元素,以及使用了多少个元素。

\n\n

最终,我想根据是否使用特定的嵌入元素来设置一些样式条件。

\n

Vin*_*y K 6

isSlotFilled函数上的函数transclude会给你想要的结果。

angular.module('App', [])
  .directive('dir', function () { 
    return {
        restrict: 'E',
        template: `
          <div ng-transclude="header"></div>
          <div class="static-content">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit.
          </div>

          <div ng-transclude="footer">
        `,
        transclude: {
            'header': '?dirHeader',
            'footer': '?dirFooter'
        },
        link: function ($s, $el, $attrs, thisCtrl, $transclude) {
          console.log($transclude.isSlotFilled('header'))
          console.log($transclude.isSlotFilled('footer'))
        }
    };
  });
Run Code Online (Sandbox Code Playgroud)

工作plnkr