【问题标题】:AngularJS: how to transclude and replace the containing elementAngularJS:如何转换和替换包含元素
【发布时间】:2013-09-11 14:26:46
【问题描述】:

我正在尝试创建一组 AngularJS 指令,它们将有条件地呈现块或内联页面内容的互斥段。例如,我设想了一种只呈现第 n 个子元素的机制:

<selector member="index">
    <div>This div is visible when $scope.index equals 0</div>
    <div>This div is visible when $scope.index equals 1</div>
    <div>This div is visible when $scope.index equals 2</div>
</selector>

但是,我的设计要求使用自定义元素标记(而不是应用于 HTML 元素的属性)来实现指令,并且在渲染完成时从 DOM 中删除这些 HTML 无效元素。因此,在上面的示例中,将保留一个匹配的 div 元素。

作为对这个概念的首次尝试,我将内置的ngIf 指令转换为使用以下基于元素的语法:

<if condition="true">
     <p>This is visible</p>
</if>

<if condition="false">
     <p>This is not visible</p>
</if>

只需将restrict 修改为E 并将被监视属性的名称更改为condition 即可。这是我对内置实现的修改版本:

application.directive("if", ['$animate', function ($animate) {
    return {
        transclude: 'element',
        priority: 1000,
        terminal: true,
        restrict: 'E',
        compile: function (element, attr, transclude) {
            return function ($scope, $element, $attr) {
                var childElement;
                var childScope;
                    $scope.$watch($attr.condition, function (value) {
                    if (childElement) {
                        $animate.leave(childElement);
                        childElement = undefined;
                    }

                    if (childScope) {
                        childScope.$destroy();
                        childScope = undefined;
                    }

                    if (toBoolean(value)) {
                        childScope = $scope.$new();
                        transclude(childScope, function (clone) {
                            childElement = clone;
                            $animate.enter(clone, $element.parent(), $element);
                        });
                    }
                });
            };
        }
    };
}]);

但是,我在消除包含 if 的元素方面并没有取得多大成功。我怀疑我需要更好地了解嵌入的工作原理,但似乎没有太多文档。

所以,如果您能建议使用正确的技术,或者为我指明一些相关教程的方向,我将不胜感激。

谢谢, 蒂姆

【问题讨论】:

  • 你看过ngSwitch吗?它是为此目的而制作的。
  • @OverZealous:是的,你说得对,ngSwitch 是一个很好的模型。然而,虽然它同时支持元素和属性模式,但元素模式在页面中留下了一个 元素,这不是有效的 HTML,是我试图克服的具体问题。

标签: angularjs angularjs-directive transclusion


【解决方案1】:

不是替换你想要的吗?

    transclude: 'element',
    priority: 1000,
    terminal: true,
    restrict: 'E',
    replace: true, // ** //

这会将if 替换为您的content

【讨论】:

  • 不幸的是,“替换”选项仅在定义模板时才有效,在这种情况下,原始元素将替换为呈现的模板。在我上面的示例中,设置 replace: true 无效。这仍然可能是解决方案的一部分,但我认为必须有一个额外的步骤来通过“编译”或“链接”功能操作或填充该模板。
  • 你为什么要补充关于使用元素,你知道你可以使用评论?
  • 对于我需要创建的一些指令,包含元素还将包含嵌套的指令元素(例如 ngSwitch),我们希望在所有指令中创建一致的语法。
猜你喜欢
  • 1970-01-01
  • 2016-04-09
  • 2018-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-14
  • 2016-02-13
  • 1970-01-01
相关资源
最近更新 更多