0

我試圖添加一個動態模板,並遇到與transclude的問題。Angularjs指令與動態模板和transclude

這是動態的模板函數:

var getTemplate = function(contentType){ 
     var template = '<button style="cursor: pointer;">' + contentType + '<ng-transclude></ng-transclude></button>' 
     return template; 
    }; 

這是代碼來調用動態模板和更新transclude:

element.html(getTemplate(attr.firstname)); 

transclude($scope.$parent, function (clone, $scope) { 
      element.children().append(clone); 
     }); 

看完整的代碼在這裏 https://plnkr.co/edit/cQBeiDkEb8KwhrFWb8iR?p=preview

查看控制檯我看到這個通知:angular.js:13920TypeError:transclude不是一個函數

結果應該包括:Go按鈕。

Go按鈕代碼在這裏:

<my-button firstname="John"><button style="cursor: pointer;"><i style="color: green;">Go</i></button></my-button> 

請幫我解決這個問題。

這是我的文檔使用:docs

非常感謝你。

+0

Transclusion已多次更改,因爲這文章寫的; 2015年的語法不適用於更多當前版本的Angular,並且很可能這種邏輯不會成爲您期望的。你應該重新思考你正在努力完成的任務,併發佈一個問題,詢問如何實現你的目標,而不是如何解決過時文章中的錯誤;除非,就是說,你使用的角度與所討論的文章完全相同*版本,這可能不是一個好主意...... – Claies

回答

2

在plunkr中沒有找到角腳本的路徑。更改爲<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>,我看到錯誤「angular.js:13920TypeError:transclude不是函數...」

+1

你檢查了控制檯嗎?我也面對這個,我改變了與我的CDN然後我得到適當的輸出,但在控制檯中,我得到了以下錯誤:「在模板中非法使用ngTransclude指令!沒有父指令,需要找到一個transclusion。」元素:「 –

+0

是的,這是一個錯誤,我已經更新了角度的新url,但ng translude顯示錯誤。 –

0

我修復了這個問題。

這是新的示例代碼: HTML代碼:

<div ng-controller="MyCtrl"> 
<my-directive title="nguyen hai dang"> 
<button>some button</button> 
<a href="#">and a link</a> 
</my-directive> 
</div> 

JS代碼:這裏

var myApp = angular.module("myApp",[]); 

function MyCtrl($scope) { 
    $scope.log=[]; 
} 

myApp.directive("myDirective", function(){ 
    return{ 
    restrict: "E", 
    replace: true, 
     transclude: true, 
    scope: { 
      title: "@" 
      }, 
     template: "<div class=\"something\" ng-transclude>{{title}} </div>" 
    }; 
}); 

校驗碼enter link description here