如何为自定义AngularJS指令使用“替换"功能? [英] How to use the 'replace' feature for custom AngularJS directives?
问题描述
为什么replace=true
或replace=false
在下面的代码中没有任何影响?
Why does replace=true
or replace=false
not have any impact in the code below?
当replace = false时为什么不显示某些现有内容"?
Why isn't the "some existing content" being displayed when replace=false?
或更谦虚地讲,您能否请您解释指令中的replace=true/false
功能是什么以及如何使用它?
Or putting it more humbly, can you kindly explain what is the replace=true/false
feature in directives and how to use it?
示例
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中查看它:
See it in Plunker here:
http://plnkr.co/edit/4ywZGwfsKHLAoGL38vvW?p=preview
推荐答案
拥有replace: true
后,您将获得以下DOM:
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>
而使用replace: false
,您会得到:
<div ng-controller="Ctrl" class="ng-scope">
<my-dir>
<div class="ng-binding">hello</div>
</my-dir>
</div>
因此,伪指令中的replace
属性是指是否应保留要应用伪指令的元素(在这种情况下为<my-dir>
),并且伪指令的模板应被附加作为其子代,
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
应用指令的元素应该由指令的模板替换(replace: true
).
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>'
};
});
在这种情况下,如果在指令的模板中有一个元素(或多个元素)具有属性ng-transclude
,则其 content 将会被替换为该元素(应用指令的对象)的原始元素内容.
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.
请参阅转换示例 http://plnkr.co/edit/2DJQydBjgwj9vExLn3Ik?p=preview
请参见此,以了解有关音译的更多信息.
See this to read more about translusion.
这篇关于如何为自定义AngularJS指令使用“替换"功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!