replace:true 如何与元素指令一起使用

How exactly replace:true works with element directives?

本文关键字:指令 一起 元素 true replace      更新时间:2023-09-26

我有以下自定义指令:

angular.module('app', [])
    .directive('smartWidget', function () {
        return{
            restrict: 'E',
            replace: true,
            template: '<div>This is the template</div>'
        }
    });

对于 HTML:

<div id="center">
        <smart-widget class="orange">blah blah</smart-widget>
</div>

使用 CSS:

.orange{
    background:orange;
}

我不明白的是,当我设置replace:true时,小部件显示为橙色背景,而replace:false则不显示。我希望这反过来工作,如下所示:

  • <div id="center"><div>This is the template</div><div>

  • 错误<div id="center"><div class="orange"><div>This is the template</div><div><div>,但我显然错了!

谁能阐明这一点?

您确定已检查属性是否也被替换?

如果在指令<some-widget class="orange red">上设置属性,该属性将被替换为,但属性将保留在那里,就像<div class="orange red">This is the template</div>

实际上发生的情况是,原始 DOM 节点的所有属性都与模板根节点中的属性合并

例如,请参见下文

angular.module('app', [])
        .directive('someWidget', function () {
            return {
                restrict: 'E',
                replace: true,
                template: '<div>This is the template</div>',
                link: function (scope, element) {
                 
                  
                }
            };
        });
.orange{color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="app">
    <some-widget class="orange red">
       
       
    </some-widget>
      </div>

针对无效 HTML 问题的更新

w3c 验证允许任何 data-* 属性,因此您可以创建"属性"指令并将其与 data-* 一起使用

例如

<div data-some-widget></div>

并将其限制为

 restrict: 'A'