2015-05-31 58 views
1

我已經在AngularJs 1.3中定義了一條transclude指令 - 但它似乎對渲染沒有任何影響。
鏈接階段的日誌語句顯示指令被調用。Transclude指令無法修改內容

的index.html

<html lang="en" ng-app="directivesApp"> 
<head> 
    <script src="js/angular.min.js"></script> 
    <script src="js/app.js"></script> 
</head> 
<body ng-controller="directiveCtrl"> 
    <label>Geography</label><input type="text" ng-model="geography"/> 
    <br> 
    <div transclude-demo> 
    <button ng-click='showGeography()'>Show Geography</button> 
    <a href="#">and a link</a> 
    </div> 
</body> 
</html> 

app.js

angular.module('directivesApp', []) 
.controller('directiveCtrl',function($scope){ 
    $scope.showGeography=function(){alert('I am here');} 
}) 
.directive('transcludeDemo',function(){ 
    return{ 
     transclude: true, 
     template: '<div ng-transclude> This is my directive content</div>', 
     link:function ($scope, element, attrs) { console.log('invoked in scope');} 
    } 
}); 

我本來期望的transclude指令替換/修改div的內容,其模板的內容。
但是,我發現div是按原樣呈現的。

這是一個transclude指令如何工作?

+1

你應該看到按鈕和一個鏈接渲染,而不是文本「這是我的指令內容」。 'ng-transclude'用橫越內容替換其元素的內容 –

+0

爲了更好地測試,請用'

This is my directive content
替換您的指示模板' –

回答

1

Transclude是用來保存已經存在的內容,所以如果你只是想要替換內容,你真正需要的是模板。你在你的例子中看不到太多,因爲你包含的div基本上是一樣的。

更換內容:

.directive('transcludeDemo',function(){ 
    return{ 
     template: '<div>This is my directive content</div>', 
     link:function ($scope, element, attrs) { console.log('invoked in scope');} 
    } 
}); 

如果您想在新/舊的內容以某種方式結合起來,加在你的模板東西ng-transclude之外,它會在組合呈現。

結合了transclude:

.directive('transcludeDemo',function(){ 
    return{ 
     transclude: true, 
     template: '<div>' + 
        '<p>This text will stay in tact</p>' + 
        '<div ng-transclude>This text will be replaced</div>' + 
        '</div>', 
     link:function ($scope, element, attrs) { console.log('invoked in scope');} 
    } 
}); 

正如評論所說,這第二個例子應該給你一個更好的瞭解所發生的情況。