如何使用指令定义的`replace`?

Fre*_*ind 80 angularjs angularjs-directive

在本文档中:http://docs.angularjs.org/guide/directive,它表示有一个replace指令配置:

template - 将当前元素替换为HTML的内容.替换过程将所有属性/类从旧元素迁移到新元素.有关更多信息,请参阅下面的创建组件部分.

javascript代码

app.directive('myd1', function(){
  return {
    template: '<span>directive template1</span>',
    replace: true
  }
});

app.directive('myd2', function(){
  return {
    template: '<span>directive template2</span>',
    replace: false
  }
});
Run Code Online (Sandbox Code Playgroud)

HTML代码

<div myd1>
  original content should be replaced
</div>
<div myd2>
  original content should NOT be replaced
</div>
Run Code Online (Sandbox Code Playgroud)

但最后一页看起来像:

directive template1
directive template2
Run Code Online (Sandbox Code Playgroud)

看来这replace不起作用.我想念什么吗?

现场演示:http://plnkr.co/edit/rGIgmjO81X2UxJohL4HM?p=preview

che*_*tts 168

你会感到困惑transclude: true,这将附加内在的内容.

replace: true表示指令模板的内容将替换声明指令的元素,在本例中为<div myd1>标记.

http://plnkr.co/edit/k9qSx15fhSZRMwgAIMP4?p=preview

例如没有 replace:true

<div myd1><span class="replaced" myd1="">directive template1</span></div>
Run Code Online (Sandbox Code Playgroud)

replace:true

<span class="replaced" myd1="">directive template1</span>
Run Code Online (Sandbox Code Playgroud)

正如您在后一个示例中所看到的,div标签确实已被替换.

  • `replace`现已弃用 (10认同)
  • @Robert确实'替换'会有替代品还是它已经消失了? (2认同)

Rya*_*ill 10

正如文档所述,'replace'确定当前元素是否被指令替换.另一个选择是它是否只是作为一个孩子基本上添加.如果查看plnkr的源代码,请注意对于第二个指令,其中replace为false,div标记仍然存在.对于第一个指令,它不是.

第一个结果:

<span myd1="">directive template1</span>
Run Code Online (Sandbox Code Playgroud)

第二个结果:

<div myd2=""><span>directive template2</span></div>
Run Code Online (Sandbox Code Playgroud)


小智 5

替换[True | 假(默认)]

影响

1.  Replace the directive element. 
Run Code Online (Sandbox Code Playgroud)

相关性:

1. When replace: true, the template or templateUrl must be required. 
Run Code Online (Sandbox Code Playgroud)