如何使用自定义 AngularJS 指令的“替换”特性?

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

为什么在 place = false 时不显示“某些现有内容”?

或者更谦虚地说,你能好心地解释一下指令中的 replace=true/false特性是什么以及如何使用它吗?

例子

JS/Angular:

<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

106158 次浏览

When you have replace: true you get the following piece of DOM:

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

whereas, with replace: false you get this:

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

So the replace property in directives refer to whether the element to which the directive is being applied (<my-dir> in that case) should remain (replace: false) and the directive's template should be appended as its child,

OR

the element to which the directive is being applied should be replaced (replace: true) by the directive's template.

In both cases the element's (to which the directive is being applied) children will be lost. If you wanted to perserve the element's original content/children you would have to translude it. The following directive would do it:

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

In that case if in the directive's template you have an element (or elements) with attribute ng-transclude, its content will be replaced by the element's (to which the directive is being applied) original content.

See example of translusion http://plnkr.co/edit/2DJQydBjgwj9vExLn3Ik?p=preview

See this to read more about translusion.

replace:true is Deprecated

From the Docs:

replace ([DEPRECATED!], will be removed in next major release - i.e. v2.0)

specify what the template should replace. Defaults to false.

  • true - the template will replace the directive's element.
  • false - the template will replace the contents of the directive's element.

-- AngularJS Comprehensive Directive API

From GitHub:

Caitp-- It's deprecated because there are known, very silly problems with replace: true, a number of which can't really be fixed in a reasonable fashion. If you're careful and avoid these problems, then more power to you, but for the benefit of new users, it's easier to just tell them "this will give you a headache, don't do it".

-- AngularJS Issue #7636


Update

Note: replace: true is deprecated and not recommended to use, mainly due to the issues listed here. It has been completely removed in the new Angular.

Issues with replace: true

For more information, see