小编典典

如何对自定义AngularJS指令使用“替换”功能?

angularjs

为什么replace=true还是replace=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


阅读 321

收藏
2020-07-04

共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,伪指令中的属性是指应用伪指令的元素(<my-dir>在这种情况下)是否应保留(replace: false),并且伪指令的模板应 附加 为其子元素,

要么

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

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

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

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

请参见翻译示例http://plnkr.co/edit/2DJQydBjgwj9vExLn3Ik?p=preview

2020-07-04