为什么replace=true
或replace=false
在下面的代码中没有任何影响?
为什么在replace=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中可以看到它:
发布于 2014-03-19 14:30:22
当你有了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>'
};
});
在这种情况下,如果在指令的模板中有一个具有ng-transclude
属性的元素(或多个元素),那么它的内容将被元素的(指令应用到的)原始内容替换。
请参阅translusion http://plnkr.co/edit/2DJQydBjgwj9vExLn3Ik?p=preview示例
要了解更多关于转换的信息,请参阅this。
https://stackoverflow.com/questions/22497706
复制相似问题