2014-03-02 36 views
1

我正在學習AngularJS。ng-transclude替換內容而不是追加

我經歷了這個video,這裏顯示了將ng-transclude放在指令模板的標籤上,會將已經存在的DOM東西附加在這個標籤中。

代碼:

<html ng-app="myApp"> 
    <head> 
     <title>TODO supply a title</title> 
     <meta charset="UTF-8"> 
     <meta name="viewport" content="width=device-width"> 
    </head> 
    <body ng-controller="AppCtrl"> 
    <panel> 
     <button>Click Me</button> 
    </panel> 

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script> 
    <script> 
      var app = angular.module('myApp', []); 
      app.controller('AppCtrl', function() { 

      }); 
      app.directive('panel', function() {  //can return a function (link) or an object 
       return { 
        restrict: 'E', 
        transclude: true, 
        template: '<span> This is my custom span</span><div class="panel" ng-transclude>this is my div</div><span>Another span follows</span>' 
       } 
      }); 
    </script> 
</body> 
</html> 

這裏的fiddle,證明了問題。

回答

2

這是最新版本的正常行爲。

Angular API on ng-transclude

"Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted." 

如果您使用Angular版本1.0.8運行您的小提琴,那麼它將像在視頻中一樣工作。

+0

感謝API鏈接 –

+2

有沒有解決辦法? – rakslice

+0

使用一個跨越功能 – Lloyd

0

使用<span>作爲transclusion主持人:

// Assign tpl var to template configuration property 
var tpl = [ 
     '<span> This is my custom span</span>', 
     '<div class="panel">', 
      '<span ng-transclude></span>', 
      ' this is my div', 
     '</div>', 
     '<span ng-switch-when="divider"></span>', 
     '<span>Another span follows</span>'', // End 
    ].join('\n');