【问题标题】:How to use the 'replace' feature for custom AngularJS directives?如何为自定义 AngularJS 指令使用“替换”功能?
【发布时间】:2014-04-25 05:11:48
【问题描述】:

为什么replace=truereplace=false 对下面的代码没有任何影响?

为什么replace=false时不显示“一些现有内容”?

或者更谦虚一点,您能否解释一下指令中的replace=true/false 功能是什么以及如何使用它?

示例

JS/角度:

<script>
    angular.module('scopes', [])
          .controller('Ctrl', function($scope) {
                $scope.title = "hello";

          })
          .directive('myDir', function() {
            return {
              restrict: 'E',
              replace: true,
              template: '<div>{{title}}</div>'
            };
      });
</script>

HTML:

<div ng-controller="Ctrl">
    <my-dir><h3>some existing content</h3></my-dir>
</div>

在 Plunker 中查看:

http://plnkr.co/edit/4ywZGwfsKHLAoGL38vvW?p=preview

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    当您拥有replace: true 时,您将获得以下 DOM:

    <div ng-controller="Ctrl" class="ng-scope">
        <div class="ng-binding">hello</div>
    </div>
    

    replace: false 你会得到这个:

    <div ng-controller="Ctrl" class="ng-scope">
        <my-dir>
            <div class="ng-binding">hello</div>
        </my-dir>
    </div>
    

    因此,指令中的replace 属性指的是应用指令的元素(在这种情况下为&lt;my-dir&gt;)是否应保留(replace: false)并且指令的模板是否应附加 作为它的孩子,

    应用指令的元素应该被指令的模板替换 (replace: true)。

    在这两种情况下,元素(应用指令的)子元素都将丢失。如果您想保留元素的原始内容/子元素,则必须对其进行转换。以下指令可以做到这一点:

    .directive('myDir', function() {
        return {
            restrict: 'E',
            replace: false,
            transclude: true,
            template: '<div>{{title}}<div ng-transclude></div></div>'
        };
    });
    

    在这种情况下,如果在指令的模板中您有一个(或多个)具有属性 ng-transclude 的元素,则其 内容 将被该元素的(应用指令的)原始元素替换内容。

    查看翻译示例http://plnkr.co/edit/2DJQydBjgwj9vExLn3Ik?p=preview

    请参阅 this 以了解有关 translusion 的更多信息。

    【讨论】:

    • 这是一个非常简单的解释。也感谢大家澄清嵌入。
    • 更重要的是,为什么不在docs.angularjs.org/guide/directive 上解释,为什么这个答案没有链接到关于该主题的明确答案?
    • @Trindaz replace 自 AngularJS v1.3 (link) 以来已被弃用。
    【解决方案2】:

    replace:true 已弃用

    来自文档:

    replace([已弃用!],将在下一个主要版本中删除 - 即 v2.0)

    指定模板应该替换的内容。默认为false

    • true - 模板将替换指令的元素。
    • false - 模板将替换指令元素的内容。

    -- AngularJS Comprehensive Directive API

    来自 GitHub:

    Caitp-- 它已被弃用,因为replace: true 存在已知的非常愚蠢的问题,其中许多问题无法以合理的方式真正解决。如果您小心并避免这些问题,那么您将获得更多权力,但为了新用户的利益,告诉他们“这会让您头疼,不要这样做”会更容易。

    -- AngularJS Issue #7636


    更新

    注意:replace: true 已弃用,不建议使用,主要是由于此处列出的问题。它已在新 Angular 中完全删除。

    替换问题:true

    有关详细信息,请参阅

    【讨论】:

    • 我一直在读到这应该在 Angular 2 中得到非官方支持,但我不知道如何激活它。谁能告诉我语法是什么?
    • @devios 我的 mdl 组件需要这样的东西,但目前正在使用remove-host 解决方法stackoverflow.com/questions/34280475/…,如果您发现在 A2 中激活 replace: true,请告诉我们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    相关资源
    最近更新 更多