angularjs – 角度指令replace = true

前端之家收集整理的这篇文章主要介绍了angularjs – 角度指令replace = true前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
为什么replace = true或replace = false在下面的代码中没有任何影响?

为什么replace = false时不显示“一些现有内容”?

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

  1. <script>
  2. angular.module('scopes',[])
  3. .controller('Ctrl',function($scope) {
  4. $scope.title = "hello";
  5.  
  6. })
  7. .directive('myDir',function() {
  8. return {
  9. restrict: 'E',replace: true,template: '<div>{{title}}</div>'
  10. };
  11. });
  12. </script>

和html

  1. <div ng-controller="Ctrl">
  2. <my-dir><h3>some existing content</h3></my-dir>
  3. </div>

看到它在plunker这里:

http://plnkr.co/edit/4ywZGwfsKHLAoGL38vvW?p=preview

当你有replace:true的时候你会得到下面的一块DOM:
  1. <div ng-controller="Ctrl" class="ng-scope">
  2. <div class="ng-binding">hello</div>
  3. </div>

而与replace:false你得到这个:

  1. <div ng-controller="Ctrl" class="ng-scope">
  2. <my-dir>
  3. <div class="ng-binding">hello</div>
  4. </my-dir>
  5. </div>

因此,指令中的replace属性指的是指令所应用的元素(在这种情况下为< my-dir>)应该保留(replace:false),而direcrive的模板应该作为子元素附加,

要么

应用指令所应用的元素应由指令的模板替换(replace:true)。

在这两种情况下,子元素(指令被应用于其中)将丢失。如果你想保持元素的原始内容/孩子,你将不得不中断它。以下指令将:

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

在这种情况下,如果在指令的模板中有一个具有属性ng-transclude的元素(或元素),它的内容将被原始内容的元素(将应用指令的元素)替换。

见转译http://plnkr.co/edit/2DJQydBjgwj9vExLn3Ik?p=preview的例子

参见this了解更多关于转换。

猜你在找的Angularjs相关文章