为什么replace = true或replace = false在下面的代码中没有任何影响?
为什么replace = false时不显示“一些现有内容”?
或者更谦虚,你能解释一下什么是指令中的replace = true / false特性以及如何使用它?
- <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这里:
当你有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),而direcrive的模板应该作为子元素附加,
要么
应用指令所应用的元素应由指令的模板替换(replace:true)。
在这两种情况下,子元素(指令被应用于其中)将丢失。如果你想保持元素的原始内容/孩子,你将不得不中断它。以下指令将:
- .directive('myDir',function() {
- return {
- restrict: 'E',replace: false,transclude: true,template: '<div>{{title}}<div ng-transclude></div></div>'
- };
- });
在这种情况下,如果在指令的模板中有一个具有属性ng-transclude的元素(或元素),它的内容将被原始内容的元素(将应用指令的元素)替换。
见转译http://plnkr.co/edit/2DJQydBjgwj9vExLn3Ik?p=preview的例子
参见this了解更多关于转换。