AngularJS:如何转换和替换包含元素

标签 angularjs angularjs-directive transclusion

我正在尝试创建一组 AngularJS 指令,它们将有条件地呈现 block 或内联页面内容的互斥段。例如,我设想了一种只呈现第 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元素将保留。

作为这个概念原型(prototype)的第一次尝试,我转换了内置的 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 的情况下并没有取得太大的成功。元素。我怀疑我需要更好地理解嵌入是如何工作的,但周围似乎没有太多文档。

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

谢谢,
蒂姆

最佳答案

不是替换你想要的吗?

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

这将取代 if与您的content

关于AngularJS:如何转换和替换包含元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18675529/

相关文章:

jquery - 指令中缺少子元素

javascript - Flexbox 调整大小事件(?)

javascript - AngularJS 嵌套指令被插入到它们假定的父元素之外

scope - angularjs 嵌入范围访问

javascript - 从 ng-messages 中提取 ng-message key

javascript - AngularJS - 限制增量和减量

javascript - 如何处理 DjangoCMS i18n URL (/en/my_page,/fr/my_page...) 和 AngularJS?

angularjs 将我自己的函数添加到现有的 ng-click

javascript - 来自指令的数据未在 ng-repeat 中显示

javascript - 在哪里以及如何修改嵌入的内容?